您的位置:首页 > 其它

169. Majority Element

2016-07-07 07:46 239 查看
思路:

设置一个counter,并且用res记录第一个数字,从第二个开始,如果这个数和前一个数是一样的,那么counter++,如果不一样,就把counter--,如果counter变成0了,就把res放到当前数字上。一遍走完,返回res就好了。

因为majority的数字超过一半,它总能中和调别的数。

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