Given an array of integers
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.
arr
, a lucky integer is an integer that has a frequency in the array equal to its value.Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Approach
Java
import java.util.HashMap;public class FindLuckyIntegerArray {public static void main(String[] args) {int[] arr = { 1, 2, 2, 3, 3, 3 };System.out.println(findLucky(arr));}static int findLucky(int[] arr) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();for (int i = 0; i < arr.length; i++)map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);int res = -1;for (Integer i : map.keySet())if (map.containsKey(i) && map.get(i) == i) {res = Math.max(res, i);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;int findLucky(vector<int> &arr){int freq[501] = {0};for (int i = 0; i < arr.size(); i++)freq[arr[i]]++;int res = -1;for (int i = 1; i < 501; i++)if (freq[i] == i){res = max(res, i);}return res;}int main(){vector<int> arr = {2, 2, 3, 4};cout << findLucky(arr);return 0;}
No comments:
Post a Comment