九度 Online Judge 算法 刷题 题目1053:互换最大最小数

题目1053:互换最大最小数

题目描述:
输入一个数n,然后输入n个数值各不相同,调换数组中最大和最小的两个数,然后输出。
输入:
测试数据有多组,输入n(1<=n<=20),接着输入n个数。
输出:
对于每组输入,输出交换后的结果。
样例输入:
2
1 3
样例输出:
3 1
来源:
2010年哈尔滨工业大学计算机研究生机试真题

code

#include <iostream>
#include<vector>
#include<algorithm>
 
using namespace std;
 
//int divisor(int a, int b) {
//  if (a == b)
//      return a;
//  else if (a > b) 
//      divisor(a - b, b);  
//  else 
//      divisor(a, b - a);
//}
 
int main() {
    int n;
    while (cin>>n) {
        vector<int> vecInt(n);
        for (int i = 0; i < n; i++) {
            int temp;
            cin>>temp;
            vecInt[i] = temp;
        }
         
        vector<int>::iterator max = vecInt.begin();
        vector<int>::iterator min = vecInt.begin();
        for(vector<int>::iterator it = vecInt.begin();it != vecInt.end();it++) {
            if (*it > *max)
                max = it;
            if (*it < *min)
                min = it;
        }
        for(vector<int>::iterator it = vecInt.begin();it != vecInt.end();it++) {  
                if (it == max) {
                    cout<<(*min);
                } else if (it == min) {
                    cout<<(*max);
                }else {
                    cout<<(*it);
                }
                if (it == vecInt.end()-1)
                    cout<<endl;
                else
                    cout<<" ";
                 
            }
        }
     
    return 0;
}
/**************************************************************     Problem: 1053     User: langzimaizan     Language: C++     Result: Accepted     Time:0 ms     Memory:1520 kb ****************************************************************/

你可能感兴趣的:(算法,面试,计算机,程序,笔试)