[Array]Majority Element

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

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

方法:充分利用主元素出现次数大于⌊ n/2 ⌋ 这个条件,根据这个条件,顺序遍历整个数组,我们可以为一个元素设置一个计数器,假设以第一个元素为例,为第一个元素设置一个count=1,表明出现过一次,然后遍历第二个元素,当第二个元素与第一个元素相等时,count++,表明出现过两次,当第二个元素与第一个元素不等时,count- -,当遍历第三个元素时如果发现count=0,则为第三个元素设置一个计数器,依次类推。
时间复杂度:O(n)
空间复杂度:O(1)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int value = nums[0];
        int count = 1;
        for(int i=1;i<nums.size();i++){
            if(count==0)
                value = nums[i];
            if(nums[i]==value)
                count++;
            else
                count--;
        }
        return value;

    }
};
posted @ 2016-07-13 08:55  U_F_O  阅读(67)  评论(0编辑  收藏  举报