Majority Element

来源:互联网 发布:家用菜刀 知乎 编辑:程序博客网 时间:2024/06/17 17:59


Given an array of size n, find the majority element. The majority element is the element that appearsmore than⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.


Solution:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count = 0;
        vector<int> a;
        a.assign(nums.size(), 0);//用来标识是否重复计数
        for(int i = 0; i < nums.size(); i++) {
            if (a[i] == 1) continue;
            for(int j = 0; j < nums.size(); j++) {
                if (a[j] == 1) continue;
                if(nums[j] == nums[i]) {
                    count++;
                    a[j] = 1;
                }
            }
            if(count > (nums.size() / 2)) return nums[i];
            else count = 0;
        }
    }
};

0 0