1 class Solution { 2 public: 3 int majorityElement(vector<int> &num) { 4 int candidate = num[0]; 5 int count = 1; 6 int len = num.size(); 7 8 for (int i=1; i<len; i++) { 9 if (count == 0) { 10 candidate = num[i]; 11 count++; 12 continue; 13 } 14 candidate == num[i] ? count++: count--; 15 } 16 return candidate; 17 } 18 };
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.
Moore voting algorithm: http://www.cs.utexas.edu/~moore/best-ideas/mjrty/
原文:http://www.cnblogs.com/lailailai/p/4440364.html