ARTS是什么? Algorithm:每周至少做一个LeetCode的算法题 Review:阅读并点评至少一篇英文技术文章 Tip:学习至少一个技术技巧 Share:分享一篇有观点和思考的技术文章

Algorithm:

  1. /**
  2. * @className: Algorithm1
  3. * @description: 在给定的数组中,找到出现次数最多的数字,出现次数相同时,返回数值最小的数字。
  4. * 样例:
  5. * Input:
  6. * [1,1,2,3,3,3,4,5]
  7. * Output:
  8. * 3
  9. * @author: Miluo
  10. * @date: 2021/2/7
  11. **/
  12. public class Algorithm1 {
  13. public static int findNumber(int[] array) {
  14. if (array.length == 1){
  15. return array[0];
  16. }
  17. //将值作为key,值的数量作为value存入map中
  18. HashMap<Integer, Integer> hashMap = new HashMap<>();
  19. for (int i : array) {
  20. if (hashMap.containsKey(i)){
  21. Integer count = hashMap.get(i);
  22. hashMap.put(i,count+1);
  23. }else{
  24. hashMap.put(i,1);
  25. }
  26. }
  27. //找到出现值数量的最大值
  28. Integer max = hashMap.entrySet().stream().map(entry -> entry.getValue()).max(Comparator.comparing(x -> x)).get();
  29. //在map中找出值数量最大值的数值存入list当中
  30. LinkedList<Integer> list = new LinkedList<>();
  31. hashMap.forEach((key,value) -> {
  32. if (value.equals(max)){
  33. list.add(key);
  34. }
  35. });
  36. if (list.size() == 1){
  37. //最多数量只有一个
  38. return list.get(0);
  39. }else {
  40. //最多数量有多个,找出数值最小的那个
  41. return list.stream().min(Integer::compareTo).get();
  42. }
  43. }
  44. }

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…”。

  1. post.setHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  2. ArrayList<NameValuePair> valuePairArrayList = new ArrayList<>();
  3. map.forEach( (x,y) -> valuePairArrayList.add(new BasicNameValuePair(x,y)));
  4. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valuePairArrayList,"utf-8");
  5. post.setEntity(urlEncodedFormEntity);

Share:

Teach Yourself Programming in Ten Years