問題:數組
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.app
解決:spa
① 將數組排序後計算出現次數。code
class Solution { //5ms
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
Arrays.sort(nums);
int count = 1;
int len = nums.length;
for (int i = 1;i < nums.length;i ++){
if (nums[i] == nums[i - 1]){
count ++;
}else {
if (count > len / 3){
res.add(nums[i - 1]);
}
count = 1;
}
}
if (count > len / 3){
res.add(nums[len - 1]);
}
return res;
}
}排序
② 推舉法,規律:任意一個數組出現次數大於n/3的衆數最多有兩個。element
class Solution { //3ms
public List<Integer> majorityElement(int[] nums) {
int num1 = 0;
int num2 = 0;
int count1 = 0;
int count2 = 0;
for (int num : nums){
if (num == num1){
count1 ++;
}else if (num == num2){
count2 ++;
}else if (count1 == 0){
num1 = num;
count1 ++;
}else if (count2 == 0){
num2 = num;
count2 ++;
}else {
count1 --;
count2 --;
}
}
count1 = 0;
count2 = 0;
for (int num : nums){
if (num == num1){
count1 ++;
}else if (num == num2){
count2 ++;
}
}
List<Integer> res = new ArrayList<>();
if (count1 > nums.length / 3) res.add(num1);
if (count2 > nums.length / 3) res.add(num2);
return res;
}
}it