问题描述: 代码如下:(1)可以使用排序的算法,然后直接返回 (2)使用map,扫描一次即可 (3)使用经典方法之消除法
import java.util.*;
public class Seventh {
public static int solve(int[] a){
Arrays.sort(a);
return a[a.length/2];
}
public static int solve1(int[] a){
Map<Integer,Integer> map=new HashMap<>();
for (int i = 0; i <a.length ; i++) {
if (map.containsKey(a[i])){
int temp=map.get(a[i]);
temp++;
if (temp>a.length/2) return a[i];
map.put(a[i],temp);
}else {
map.put(a[i],1);
}
}
int res=-1;
for (Map.Entry<Integer, Integer> entry:map.entrySet()) {
if (entry.getValue()>a.length/2) res=entry.getKey();
}
return res;
}
public static int solve3(int[] a){
int target=a[0];
int count=1;
for (int i = 1; i <a.length ; i++) {
if (count==0){
target=a[i];
count=1;
continue;
}
if (a[i]!=target) count--;
else count++;
}
return target;
}
public static void main(String[] args) {
int[] a={0,1,0,1,0};
System.out.println(Arrays.toString(a));
System.out.println(solve(a));
System.out.println(solve1(a));
System.out.println(solve3(a));
}
}
结果如下:
|