给你一个非递减的 有序 整数数组,已知这个数组中恰好有一个整数,它的出现次数超过数组元素总数的 25%。
请你找到并返回这个整数
方法一:遍历
class Solution {
public int findSpecialInteger(int[] arr) {
int len = arr.length;
int res = arr[0];
int count=0;
for(int num : arr){
if(res == num){
count++;
if(count > (len/4)){
break;
}
}else{
res = num;
count = 1;
}
}
return res;
}
}
方法二:用HashMap计数,key为数组中的数,value为出现次数
class Solution {
public int findSpecialInteger(int[] arr) {
int len = arr.length;
Map<Integer,Integer> map = new HashMap<>();
int res=0;
for(int num : arr){
// 如果map中已经存放该数,则计数加一,否则默认为0
map.put(num,map.getOrDefault(num,0)+1);
// 同时判断数量是否超过25%
if(map.get(num) > (len/4)){
res = num;
}
}
return res;
}
}