LeetCode/剑指Offer/ 数组中出现次数超过一半的数字
剑指Offer其他题目代码
【摩尔投票】
关于摩尔投票在知乎上看到了一个非常形象的回答 如何理解摩尔投票算法? - 胡新辰的回答 - 知乎
总结一下就是,几个部落打仗,非我族类就同归于尽,最后哪个部落还有人,哪个部落就赢了。
【举例】
战场 | 候补士兵 |
---|---|
[] | 7, 7, 5, 7, 5, 1, 5, 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[7] | 7, 5, 7, 5, 1, 5, 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[7, 7] | 5, 7, 5, 1, 5, 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[7, | 7, 5, 1, 5, 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[7,7] | 5, 1, 5, 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[7, | 1, 5, 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[ | 5, 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[5] | 7, 5, 5, 7, 7, 7, 7, 7, 7 |
[ | 5, 5, 7, 7, 7, 7, 7, 7 |
[5] | 5, 7, 7, 7, 7, 7, 7 |
[5, 5] | 7, 7, 7, 7, 7, 7 |
[5, | 7, 7, 7, 7, 7 |
[ | 7, 7, 7, 7 |
[7] | 7, 7, 7 |
[7, 7] | 7, 7 |
[7, 7, 7] | 7 |
[7, 7, 7, 7] |
【代码】
//时间复杂度:O(n);
//空间复杂度:O(1);
class Solution {
public static int majorityElement(int[] nums) {
int res = nums[0];
int count = 0;
for (int num : nums) {
if (count == 0) {
res = num;
}
count += (res == num) ? 1 : -1;
}
return res;
}
}
【其他解法】
1.借用HashMap计数
//时间复杂度:O(n);
//空间复杂度:O(n);
class Solution {
public static int majorityElement(int[] nums) {
int res = nums[0];
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num) == false) {
map.put(num, 1);
} else {
int count = map.get(num);
if (count == nums.length / 2) {
res = num;
break;
}
map.put(num, count + 1);
}
}
return res;
}
}
2.排序,中间位置的数即为结果
//时间复杂度:O(nlogn);
//空间复杂度:O(logn);自己动手写个堆排可以降低空间复杂度
class Solution {
public static int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}