先上题目
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]
代码部分一(超时)
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<String> list =new ArrayList();
List<Integer> resultList =new ArrayList();
int n =nums.length;
int index =0;
list.add(0,"T");
for(int i =0;i <nums.length;i++){
int temp =0;
int count =0;
if(list.get(i) !="F"){
for(int j =0;j<nums.length;j++){
if(nums[i] ==nums[j]){
list.add(j,"F");
count++;
}else{
list.add(j,"T");
}
}
if(count >n/3){
index++;
if(index ==2){
if(temp ==nums[i]){
continue;
}
}
temp =nums[i];
resultList.add(nums[i]);
}
}
}
return resultList;
}
}
代码部分二(3ms)
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> resultList = new ArrayList();
int res_one =0, res_two =0,cou_one =0,cou_two =0;
int n =nums.length/3;
if(nums == null || nums.length == 0){
return resultList;
}
for(int num:nums){
if(num ==res_one){
cou_one++;
}else if(num ==res_two){
cou_two++;
}else if(cou_one ==0){
res_one =num;
cou_one=1;
}else if(cou_two ==0){
res_two =num;
cou_two=1;
}else{
cou_one--;
cou_two--;
}
}
cou_one =0;
cou_two =0;
for (int i : nums) {
if (i ==res_one) ++cou_one;
if (i ==res_two) ++cou_two;
}
if(cou_one >n) resultList.add(res_one);
if(cou_two >n&&res_one !=res_two) resultList.add(res_two);
return resultList;
}
}
思路:还是利用摩尔投票的思路,同时寻找两个众数,且其互不影响。
1.设置标签cou_one对res_one进行计数,设置标签cou_two对res_two进行计数
2.当标签为0时,说明当前"假定众数"<n/3,更换众数。(众数1+众数2+其他=数组n)
3.当读取的数为res_one时,cou_one++;当读取的数为res_two时,cou_two++;为其他时cou_one--,cou_two--。
4.判定获得的"假定众数"是否为真众数(在数组中的个数超过n/3)