Leetcode 1394. Find Lucky Integer in an Array
Given an array of integers arr
, a lucky integer is an integer which has a frequency in the array equal to its value. Write a function to 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.
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
class Solution {
public:
int findLucky(std::vector<int>& arr) {
// Hashmap to store the frequency of each number
std::unordered_map<int, int> freqMap;
// Calculate frequencies
for (int num : arr) {
freqMap[num]++;
}
int result = -1; // Default result if no lucky integer is found
// Iterate through the hashmap to find lucky integers
for (const auto& elem : freqMap) {
if (elem.first == elem.second) {
result = std::max(result, elem.first);
}
}
return result;
}
};
// Example usage:
// int main() {
// Solution sol;
// std::vector<int> arr = {2, 2, 3, 4};
// std::cout << sol.findLucky(arr) << std::endl; // Output: 2
// return 0;
// }
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?