169. 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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2
 
 

解题思路:

我们可以用map来存储值与数量的关系,但是那样的空间复杂度为O(n)

这里学习一种O(1)的空间复杂度的解法:摩尔投票法(Moore Voting),能使用的前提是:一定有众数存在!

我们首先设定第一个数字为众数候选者,设定计数器cnt为1

然后这个时候遍历下一个数字,若下一个数字与候选者相等:cnt自增1;若不想等:自减一

在每次遍历前我们要先检查当前计数器的值:

  若计数器为0,则设置当前数字位候选数字。

 

 

代码:

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

 

posted @ 2018-06-26 05:46  妖域大都督  阅读(89)  评论(0编辑  收藏  举报