classSolution { public: unordered_map <int, int> m; intfindLucky(vector<int>& arr){ for (auto x: arr) ++m[x]; int ans = -1; for (auto [key, value]: m) { if (key == value) { ans = max(ans, key); } } return ans; } };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: deffindLucky(self, arr: List[int]) -> int: m = dict() for x in arr: m[x] = m.get(x, 0) + 1 ans = -1 for (key, value) in m.items(): if key == value: ans = max(ans, key) return ans
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicintfindLucky(int[] arr) { Map<Integer, Integer> m = newHashMap<Integer, Integer>(); for (int x : arr) { m.put(x, m.getOrDefault(x, 0) + 1); } intans= -1; for (Map.Entry<Integer, Integer> entry : m.entrySet()) { intkey= entry.getKey(), value = entry.getValue(); if (key == value) { ans = Math.max(ans, key); } } return ans; } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11
var findLucky = function(arr) { let m = {} arr.forEach((x) => { m[x] = (x in m ? m[x] + 1 : 1) }) let ans = -1 Object.keys(m).forEach((key) => { ans = (key == m[key] ? Math.max(key, ans) : ans) }) return ans };