java面试常见算法总结
1、 一个int[]数组 如何打印出重复次数前5的元素及重复次数
/**
* 排序
* @author v_liuwen
* @date 2019/3/5
*/
public class SortDemo {
public static void main(String[] args) {
int[] nums = new int[]{1,3,7,4,9,2,3,4,3,4,5,3,6,3,7,5,4,5,6,7,9,4};
sort(nums);
}
public static void sort(int[] nums){
Map<Integer,Integer> map = new HashMap<>();
Arrays.stream(nums).forEach(num ->{
if(map.get(num)==null){
map.put(num,1);
}else {
map.put(num,map.get(num)+1);
}
});
map.forEach((k,v) ->{
System.out.println("key:"+k+" value:"+v);
});
//按键排序
// System.out.println("---------------按键排序--------------------");
// Map<Integer,Integer> resultKey = map.entrySet()
// .stream().sorted(Map.Entry.comparingByKey())
// .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(oldValue,newValue) ->oldValue,LinkedHashMap::new));
// System.out.println(resultKey);
//按值排序
System.out.println("---------------按值排序--------------------");
Map<Integer,Integer> resultValue = map.entrySet()
.stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(oldValue,newValue) ->oldValue,LinkedHashMap::new));
Integer count = 5;
for(Integer key:resultValue.keySet()){
if(count<1){
break;
}
System.out.println("key:"+key+" value:"+resultValue.get(key));
count--;
}
}
}
打印结果
key:1 value:1
key:2 value:1
key:3 value:5
key:4 value:5
key:5 value:3
key:6 value:2
key:7 value:3
key:9 value:2
---------------按值排序--------------------
key:3 value:5
key:4 value:5
key:5 value:3
key:7 value:3
key:6 value:2
持续更新中。。。