Given an integer array of size n, find all elements that appear more
than ⌊ n/3 ⌋ times.Note: The algorithm should run in linear time and in O(1) space.
Example 1:
Input: [3,2,3] Output: [3] Example 2:
Input: [1,1,1,3,3,2,2,2] Output: [1,2]
题目:求解数组中数字出现次数大于n/3的数字,线性时间复杂度以及O(1)的空间
这是array类的题目中做过的最有心机的一道题,对时间的线性要求以及不能使用数字决定了这道题一定是有窍门的,这就是出现次数要大于n/3,这样的数字如果存在的话,顶多会有两个。
使用两个临时变量num1和num2作为出现次数最多的两个数,以及c1和c2分别记录出现次数,第一次遍历数组时,当num1出现是c1++,当num2出现时,c2++,都没有出现时,c1–,c2–。这样遍历过一遍数组后,如果存在符合条件的数字,由于她的出现次数大于1/3,所以num1或num2中肯定会存在一个。
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> ret = new ArrayList();
int n = nums.length;
if(n < 1) {
return ret;
}
int times = n/3;
int num1 = nums[0];
int num2 = nums[0];
int c1 = 0;
int c2 = 0;
for(int i = 0; i < n ; i++) {
if(num2 != nums[i] && (c1 == 0 || num1 == nums[i])) {
c1++;
num1=nums[i];
} else if(c2 == 0 || num2 == nums[i]) {
c2++;
num2 = nums[i];
} else {
c1--;
c2--;
}
}
c1= 0;
c2 = 0;
for(int i = 0; i < n ; i++) {
if(nums[i] == num1) {
c1++;
} else if(nums[i] == num2) {
c2++;
}
}
if(c1 > times) {
ret.add(num1);
}
if(c2 > times ) {
ret.add(num2);
}
return ret;
}
}