- 牛客链接:数组中出现次数超过一半的数字
- 题目:给一个长度为 n 的数组,数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。数据范围:n \le 50000n≤50000,数组中元素的值 0 \le val \le 100000≤val≤10000要求:空间复杂度:O(1),时间复杂度 O(n)
- 思路:(这里提供三种思路)
- 思路一:使用哈希map,利用<数字,出现次数>的映射关系,最后统计得出出现次数超过一半的数字。
- 思路二:对数组内的数组进行排序,出现次数最多的数字一定在中间位置,然后再检测该数字是否满足出现次数超过一半的要求。
- 思路三: 要找到数据出现次数超过一半,所以我们同时去掉两个不同的数字,最后留下的就是需要找到的数字。
//思路一的具体实现如下
import java.util.Map;
import java.util.HashMap;
public class TEST {
public int MoreThanHalfNum_Solution(int [] array) {
if(array == null){
return 0;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < array.length; i++){
if(map.containsKey(array[i])){
int count = map.get(array[i]);
count++;
map.put(array[i], count);
}else{
map.put(array[i], 1);
}
if(map.get(array[i]) > array.length/2){
return array[i];
}
}
return 0;
}
}
//思路二的具体实现如下
import java.util.Arrays;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array == null){
return 0;
}
Arrays.sort(array);
int target = array[array.length/2];
int count = 0;
for(int i = 0; i < array.length; i++){
if(target == array[i]){
count++;
}
}
if(count > array.length/2){
return target;
}
return 0;
}
}
//思路三的具体实现如下
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int target = array[0];
int times = 1;
for(int i=1;i<array.length;i++){
if(times==0) {
target = array[i];
times=1;
}
else if(array[i]==target){
times++;
}
else{
times--;
}
}
times=0;
for(int i=0;i<array.length;i++){
if(array[i]==target)
times++;
}
return times>array.length/2?target:0;
}
}