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.

 

假设不同数字相互抵消,那么最后剩下的数字,就是我们要找的多数元素。

我们可以把这个过程打个比方,比如现在多军对峙,假设阵营A士兵人数比其他方的人数都多,阵营A士兵能以一杀一,那么只要阵营A士兵不杀自己人(相同数字),去杀不同阵营的人(不同数字),那么最后剩下的那些士兵,就是阵营A的士兵。


作者:ni-wo-shan-dian-zi-xiang-feng-3e
链接:https://leetcode.cn/problems/majority-element/solution/tong-su-yi-dong-mo-er-tou-piao-fa-by-ni-h4m1b/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

 

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int res = nums[0];
        int res2 ;
        int cnt = 1;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i]==res) {
                cnt++;
            } else {
                cnt--;
                if (cnt <= 0) {
                res = nums[++i];
                cnt++;
                }
            }
        }
        return res;
        //sort(nums.begin(),nums.end());
        //return nums[nums.size()/2];
    }
};

 

posted @ 2018-04-14 23:11  乐乐章  阅读(125)  评论(0编辑  收藏  举报