Majority Element

来源:互联网 发布:金牛考勤软件电话 编辑:程序博客网 时间:2024/04/25 08:39

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.

Use Moore's voting. 

1. Use num[0] as the candidate, and maintain a counter of how many times this candidate shows

2. For each element, if it equals to candidate, count++; if it doesn't equal to candidate, either replace the candidate(count == 0) or count-- (count > 0)

3. In the end of the loop, the left candidate is the result.

    public int majorityElement(int[] num) {        int candidate = num[0];        int count = 1;        for (int i = 1; i < num.length; i++) {            if (num[i] == candidate) {                count++;            } else {                if (count == 0) {                    candidate = num[i];                    count = 1;                } else {                    count--;                }            }        }        return candidate;    }


0 0