首页 > 其他 > 详细

第一章 练习题 7 判断是否有数量过半的数

时间:2020-04-17 11:20:07      阅读:61      评论:0      收藏:0      [点我收藏+]
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;



bool fun(vector<int> v, int& x) {
    vector<int> v1 = v;
    sort(v1.begin(), v1.end(), greater<int>());
    vector<int>::iterator it1, it2;
    int size = v1.size();
    int count = 0;
    it2 = v1.begin();
    for (it1 = v1.begin(); it1 != v1.end(); it1++) {
        if (*it1 != *it2) {
            it2 = it1;
            count = 1;
        }
        else {
            count++;
            if (count > size / 2) {
                x = *it1;
                return true;
            }
        }
    }
    return false;

}


int main() {
    vector<int> v;
    int a[] = { 2,9,6,4,5,6,2 };
    for (int i = 0; i < 7; i++) {
        v.push_back(a[i]);
    }
    int x = -1;
    bool res;
    res = fun(v, x);
    cout << res << ";" << x << endl;
    return 0;
}

 

第一章 练习题 7 判断是否有数量过半的数

原文:https://www.cnblogs.com/SlowIsFast/p/12718117.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!