Java基础:HashMap的用法
生活随笔
收集整理的這篇文章主要介紹了
Java基础:HashMap的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數組中出現次數超過一半的數字
數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度為9的數組{1,2,3,2,2,2,5,4,2}。由于數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。
import java.util.*; public class Solution {public int MoreThanHalfNum_Solution(int[] array) {int len = array.length / 2;//定義一個HashMapMap<Integer, Integer> map = new HashMap<>();for (int i = 0; i < array.length; i++) {//map.put(key,value)在map中添加鍵值對(key,value)/*map.getOrDefault(key, 0);1.如果map中存在key,返回key對應的value2.如果map中不存在key,返回默認值0*/map.put(array[i], map.getOrDefault(array[i], 0) + 1);}Iterator iterator = map.entrySet().iterator();while (iterator.hasNext()) {Map.Entry entry = (Map.Entry) iterator.next();Integer key = (Integer) entry.getKey();Integer value = (Integer) entry.getValue();if (value > len)return key.intValue();}return 0;} }總結
以上是生活随笔為你收集整理的Java基础:HashMap的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020新年发红包Java实现
- 下一篇: 【Java开发】生成二维码