Majority Element

来源:互联网 发布:2016网络诈骗事件 编辑:程序博客网 时间:2024/06/07 10:31

题目

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.

分析

这是在分治中的一个问题;无疑,所求的这个数出现的次数大于等于其他数出现的次数之和;所以可以用一个O(n)的方法来解决这个问题:
从头开始,记当前数字为cur;出现次数为1;然后开始遍历,若出现相同的数,计数加一,否则减一;如果记数减到小于0;则记cur为此时遍历到的数,最后剩下的cur必定是出现次数大于等于⌊ n/2 ⌋的那个数;

解答

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