您的位置:首页 > 其它

LeetCode Majority Element

2015-10-08 15:27 183 查看
题目:

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.
题意:

就是给你一个Array,然后求其中最大的元素。所谓最大的元素也就是指其中出现次数大于 ⌊ n/2 ⌋的数。

参考《编程之美》,发现有一种非常简单的方法可以来实现这个过程,那就是先不用排序,每一个删除两个不同的ID,在剩下的ID中,出现次数多于

⌊ n/2 ⌋的数必然还是会超过总数的一半,所以我们可以考虑将这个问题以大化小,然后逐层降低总数,使得这个时间复杂度降为O(n),就行了

public int majorityElement(int[] nums)
{
int length = nums.length;
int candidate = 0;
int nTimes,i;
for(i = nTimes = 0; i < length; i++)
{
if(nTimes == 0)
{
candidate = nums[i];
nTimes = 1;
}
else
{
if(candidate == nums[i])
nTimes ++;
else
nTimes --;
}
}
return candidate;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: