LeetCode之求众数

我的思路是用map记录数字的出现次数,遍历vector,当某个数字出现的次数超过一半就退出循环。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int half = nums.size() / 2;
        int ans = 0;
        map<int , int>flag;
        for( int i = 0 ; i < nums.size() ; i++ ){
            flag[nums[i]]++;
            if( flag[nums[i]] > half ){
                ans =  nums[i];
                break;
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/wuhenglan/article/details/88317149