九度 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
****************************************************************/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值