ARTS是什么? Algorithm:每周至少做一个LeetCode的算法题 Review:阅读并点评至少一篇英文技术文章 Tip:学习至少一个技术技巧 Share:分享一篇有观点和思考的技术文章
Algorithm:
/**
* @className: Algorithm1
* @description: 在给定的数组中,找到出现次数最多的数字,出现次数相同时,返回数值最小的数字。
* 样例:
* Input:
* [1,1,2,3,3,3,4,5]
* Output:
* 3
* @author: Miluo
* @date: 2021/2/7
**/
public class Algorithm1 {
public static int findNumber(int[] array) {
if (array.length == 1){
return array[0];
}
//将值作为key,值的数量作为value存入map中
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i : array) {
if (hashMap.containsKey(i)){
Integer count = hashMap.get(i);
hashMap.put(i,count+1);
}else{
hashMap.put(i,1);
}
}
//找到出现值数量的最大值
Integer max = hashMap.entrySet().stream().map(entry -> entry.getValue()).max(Comparator.comparing(x -> x)).get();
//在map中找出值数量最大值的数值存入list当中
LinkedList<Integer> list = new LinkedList<>();
hashMap.forEach((key,value) -> {
if (value.equals(max)){
list.add(key);
}
});
if (list.size() == 1){
//最多数量只有一个
return list.get(0);
}else {
//最多数量有多个,找出数值最小的那个
return list.stream().min(Integer::compareTo).get();
}
}
}
Review:
Java TreeMap Vs HashMap With Examples
该文章用例子简单清楚的描述了TreeMap和HashMap的异同点,很适合初学者学习。
在迭代过程中修改了原始Map,则会引发运行时异常ConcurrentModificationException,使用迭代器iterator.remove()。
Tip:
当请求content-type:application/x-www-form-urlencoded时,需要设置Post请求的Entity属性为UrlEncodedFormEntity,该类接收数据类型为NameValuePair的list,消息体内容为“k1=v1&k2=v2…”。
post.setHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
ArrayList<NameValuePair> valuePairArrayList = new ArrayList<>();
map.forEach( (x,y) -> valuePairArrayList.add(new BasicNameValuePair(x,y)));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valuePairArrayList,"utf-8");
post.setEntity(urlEncodedFormEntity);