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.

找出数列中个数超过一半的数,假定数列不为空且该数一定存在。

代码如下:

 class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
int index = ;
int candidate = nums[];
for(int i = ; i < n; i++)
{
if(candidate == nums[i])
{
index ++;
}
else
{
index --;
}
if(index < )
{
candidate = nums[i];
index = ;
}
}
return candidate;
}
};
上一篇:关于jQuery中toggle()函数的使用


下一篇:【HDOJ】1547 Bubble Shooter