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.

  1. int majorityElement(vector<int> &num) {
  2. int nSize = num.size();
  3. int time = 0;
  4. int curValue = -1;
  5. for(int i=0;i<nSize;i++) {
  6. if(time == 0) {
  7. curValue = num[i];
  8. time = 1;
  9. } else {
  10. if(num[i] == curValue) {
  11. time++;
  12. } else {
  13. time--;
  14. }
  15. }
  16. }
  17. return curValue;
  18. }
posted @ 2014-12-23 19:39  purejade  阅读(84)  评论(0)    收藏  举报