LeetCode---Majority Element II

来源:互联网 发布:农村淘宝 土豪村 编辑:程序博客网 时间:2024/06/18 13:22

题目大意:给出一个数组,找出数组中元素出现次数大于数组1/3规模的元素,要求算法运行时间在线性时间内,空间复杂度为O(1);

算法思想:

1.首先对数组排序。

2.利用upper_bound()算法找出出现次数大于数组规模1/3的元素。

代码如下:

class Solution {public:    vector<int> majorityElement(vector<int>& nums) {        vector<int> res;        int nums_size=0;        if(nums.size()==0) return res;        int times=nums.size()/3;        sort(nums.begin(),nums.end());        vector<int>::iterator pos=nums.begin(),prepos=nums.begin();        int value=*pos;        while(pos!=nums.end()){            pos=upper_bound(nums.begin(),nums.end(),value);            if(pos-prepos>times) res.push_back(value);            value=*pos;            prepos=pos;        }        return res;            }};


0 0