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];
}
}