leetcode 169

169. 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 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int n = nums.size();
 5         int index = 0;
 6         int candidate = nums[0];
 7         for(int i = 0; i < n; i++)
 8         {
 9             if(candidate == nums[i])
10             {
11                 index ++;
12             }
13             else
14             {
15                 index --;
16             }
17             if(index < 0)
18             {
19                 candidate = nums[i];
20                 index = 0;
21             }
22         }
23         return candidate;
24     }
25 };

 

posted @ 2016-11-08 10:58  花椰菜菜菜菜  阅读(161)  评论(0编辑  收藏  举报