leetcode-182 Zhou season -5368. Find the lucky number in the array

Subject description:

 

 

 python submit:

from typing import List
import collections
class Solution:
    def findLucky(self, arr: List[int]) -> int:
        dic = collections.Counter(arr)
        ans = -1
        for i,v in dic.items():
            if i == v:
                ans = max(ans,i)
        return ans

java:

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

 

Guess you like

Origin www.cnblogs.com/oldby/p/12592224.html