Description:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
Solution:
空间复杂度都要O(1),着实捉急了一下
后来百度到了一个算法,摩尔投票法,维基百科链接在这里 Boyer-Moore Majority Vote Algorithm
貌似很多LeetCode上面medium级别的题目,都要用到一些特殊的算法,包括前面遇到的manacher算法 Longest Palindromic Substring 编译原理中学到的逆波兰表达式 Basic Calculator
import java.util.*;
public class Solution {
public List<Integer> majorityElement(int[] nums) {
LinkedList<Integer> list = new LinkedList<Integer>();
int n = nums.length;
if (n == 0)
return list;
int candidateA = 0, candidateB = 0, countA = 0, countB = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == nums[candidateA]) {
countA++;
} else if (nums[i] == nums[candidateB]) {
countB++;
} else if (countA == 0) {
candidateA = i;
countA = 1;
} else if (countB == 0) {
candidateB = i;
countB = 1;
} else {
countA--;
countB--;
}
}
countA = 0;
countB = 0;
for (int i = 0; i < n; i++)
if (nums[i] == nums[candidateA])
countA++;
else if (nums[i] == nums[candidateB])
countB++;
if (countA * 3 > n)
list.add(nums[candidateA]);
if (countB * 3 > n)
list.add(nums[candidateB]);
return list;
}
}