Fri. Apr 19th, 2024

Given an array of integers arr, a lucky integer is an integer which 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
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
class Solution {
    public int findLucky(int[] arr) {
        if(arr.length == 0) return -1;
        Map<Integer,Integer> luckymap = new TreeMap<Integer,Integer>();
        for(int i:arr){
            luckymap.put(i,luckymap.getOrDefault(i,0)+1);
        }
        
        List<Integer> luckylist = new ArrayList<Integer>();
        for(int i:luckymap.keySet()){
            if(i == luckymap.get(i)) luckylist.add(i); 
        }
        
        //System.out.println(luckylist);
        if(luckylist.size()<1)
            return -1;
        else
            return luckylist.get(luckylist.size()-1);
    }
}