Type Here to Get Search Results !

Find Lucky Integer in an Array | | LeetCode Problems And Solution | CodingHumans |

0

Find Lucky Integer in an Array
Difficulty:easy
Topic:Array

Problem 

Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.

Task 

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.

Example 2:

Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.

Example 3:

Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.

Example 4:

Input: arr = [5]
Output: -1
Example 5:

Input: arr = [7,7,7,7,7,7,7]
Output: 7


Constraints:

1 <= arr.length <= 500

1 <= arr[i] <= 500




Recommended: Please try your approach on your integrated development environment (IDE) first, before moving on to the solution.

Few words from CodingHumans : Don't Just copy paste the solution, try to analyze the problem and solve it without looking by taking the the solution as a hint or a reference . Your understanding of the solution matters.

HAPPY CODING 😁



Solution:
( Java )

import java.util.*;
public class Solution {

public static void main(String[] args) {
int arr[]= {1,2,2,3,3};
Solution s1=new Solution();
System.out.println(s1.findLucky(arr));
}
public int findLucky(int[] arr) {
        int largest = -1;
Map < Integer, Integer> map = new HashMap<Integer, Integer>();
for ( int i = 0 ; i < arr.length; i++) {
if(map.containsKey(arr[i])) {
                map.put(arr[i], map.get(arr[i]) + 1);
} else {
map.put(arr[i], 1);
}
}
for(int i : map.keySet()) {
if( i == map.get(i)) {
largest = Math.max(largest, i);
}
}
return largest;
        }
}



Solution:
( c++ )



class Solution {
public:
 int findLucky(vector<int>& arr) {
        unordered_map<int, int> mp;
        int lucky = -1;
        for (int i : arr) ++mp[i];
        for (auto it=mp.begin(); it!=mp.end(); ++it) {
            if (it->second == it->first)
                lucky = max(lucky, it->first);
        }
        return lucky;
    }
};

If you have any doubts regarding this problem or  need the solution in other programming languages then leave a comment down below .                 


Post a Comment

0 Comments

Top Post Ad

Below Post Ad