标签:
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.
解法:
As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0.
When we move the pointer forward over an element e:
When we are done, the current candidate is the majority element, if there is a majority.
public class Solution { public int majorityElement(int[] num) { int sum=0; int result=0; for(int i=0;i<num.length;i++){ if(sum==0){ result=num[i]; sum++; } else if(result==num[i]){ sum++; if(sum>num.length/2){ return result; } } else sum--; } return result; } }
标签:
原文地址:http://www.cnblogs.com/lilyfindjobs/p/4186491.html