每日一练-leetcode

找出数组中的幸运数

在整数数组中,如果一个整数的出现频次和它的数值大小相等,我们就称这个整数为「幸运数」。

给你一个整数数组 arr,请你从中找出并返回一个幸运数。

如果数组中存在多个幸运数,只需返回 最大 的那个。
如果数组中不含幸运数,则返回 -1 。
 

 

 解法:HahsMap

将数组中的数存储完整,然后遍历map表

class Solution {
    public int findLucky(int[] arr) {
        if(arr.length == 0){
            return -1;
        }
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i : arr){
            map.put(i,map.getOrDefault(i,0)+1);
        }
        int ans = -1;
        for(Map.Entry<Integer,Integer> entry:map.entrySet()){
            int key = entry.getKey();
            int value = entry.getValue();
            if(key == value){
                ans = Math.max(ans, key);
            }
        }
        return ans;

    }
}

  此题中有两个值得注意的点:

1)map.getOrDefault(i,0)此函数要不的到i的值即get(i),要不返回0

2)for(Map.Entry<Integer,Integer> entry:map.entrySet());此方法为遍历map的一种形式<key,vaule>遍历

3)entry.getKey();entry.getValue()

posted @ 2021-09-09 12:01  YBINing  阅读(34)  评论(0编辑  收藏  举报