Majority Element

来源:互联网 发布:网络水晶头怎么接 编辑:程序博客网 时间:2024/04/24 21:41

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.

思路:如果不相同就成对删除,剩下的就是the majority element。 如何成对删除,可以用一个计数器,相同就+,不同就-,为0的时候更新candidate。

Ref:http://www.cnblogs.com/ganganloveu/p/4177690.html

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


0 0