題目描述
數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度爲9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。
題目鏈接:牛客網
解題思路
多數投票問題,可以利用 Boyer-Moore Majority Vote Algorithm 來解決這個問題,使得時間複雜度爲 O(N)。
使用 cnt 來統計一個元素出現的次數,當遍歷到的元素和統計元素相等時,令 cnt++,否則令 cnt–。如果前面查找了 i 個元素,且 cnt == 0,說明前 i 個元素沒有 majority,或者有 majority,但是出現的次數少於 i / 2 ,因爲如果多於 i / 2 的話 cnt 就一定不會爲 0 。此時剩下的 n - i 個元素中,majority 的數目依然多於 (n - i) / 2,因此繼續查找就能找出 majority。
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,2,2,2,5,4,2};
int num = moreThanHalfNum_Solution(arr);
System.out.println(num);
}
public static int moreThanHalfNum_Solution(int[] nums) {
int majority = nums[0];
for (int i = 1,cnt = 1;i < nums.length;i++) {
cnt = nums[i] == majority ? cnt + 1 :cnt - 1;
if (cnt == 0) {
majority = nums[i];
cnt = 1;
}
}
int cnt = 0;
for (int val : nums) {
if (val == majority) {
cnt++;
}
}
return cnt > nums.length / 2 ? majority : 0;
}
}