题目:
解决方法:排序、哈希、候选法
1.排序
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Arrays.sort(array);
int len = array.length;
int cnt =0;
int res = array[len/2];
for(int i =0;i<len;i++)
if(array[i]==res)
cnt++;
if(cnt>len/2)
return res;
return 0;
}
}
时间复杂度:O(nlogn)
空间复杂度:O(1)
2.哈希
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer,Integer> map = new HashMap<>();
int cnt = 0;
for(int i =0;i<array.length;i++){
if(!map.containsKey(array[i]))
cnt = 0;
else
cnt = map.get(array[i]);
if(cnt==array.length/2)
return array[i];
map.put(array[i],cnt+1);
}
return 0;
}
}
时间复杂度:O(n)
空间复杂度:O(n)
3.候选法
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int len = array.length;
int res = -1;
int cnt = 0;
for(int i =0;i<len;i++){
if(cnt==0){
res = array[i];
cnt++;
}
else{
if(array[i]==res)
cnt++;
else
cnt--;
}
}
if(cnt==0)
return 0;
else
return res;
}
}
时间复杂度:O(n)
空间复杂度:O(1)