您的位置:首页 > 其它

LeetCode 169. Majority Element

2017-08-30 12:57 405 查看
问题:

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.
Credits:

Special thanks to @ts for adding this problem and creating all test cases.

问题描述:

找出当前数组中出现的次数最多的,其中最多的那个数出现的次数一定超过[n/2].

问题分析:

这个这个问题如果用一般的方法做就是先用一个Map统计出每个数值出现的次数,然后找出最大的那一个。

但是这个问题中添加了一个额外的条件是  出现最多的数出现的次数超过了[n/2].

这样就有一种额外的解法:

找出两个不同的数都减一,知道最后剩下的哪个数。由于出现最多的数出现的次数超过了[n/2].那么无论如何排列进行减,最终留下的一定是出现最多的哪个数。

代码实现:

if (nums == null || nums.length == 0) {
return 0;
}

int maxCount = 0;
int num = -1;

for (int i = 0; i < nums.length; i++) {

if (maxCount == 0) {
num = nums[i];
maxCount = 1;
} else if (num != nums[i]) {

maxCount--;
} else {
maxCount++;
}
}

return num;
正常解法是先统计,然后进行找出出现次数最多的解法 。这里用了一种做减法的思路,同时由于有了>[n/2]这个条件使得这种实现变得正常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: