Sponsored
Sponsored
This approach involves using a hash map (or dictionary) to store the frequency of each integer in the array. Once frequencies are calculated, iterate through the map to find integers whose value is equal to their frequency, and track the maximum of such values.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), since the frequency array is of constant size (501).
1def findLucky(arr):
2 freq = {}
3 for num in arr:
4 freq[num] = freq.get(num, 0) + 1
5 maxLucky = -1
6 for num, count in freq.items():
7 if num == count and num > maxLucky:
8 maxLucky = num
9 return maxLucky
10
11arr = [1, 2, 2, 3, 3, 3]
12print(findLucky(arr))
In this Python solution, a dictionary is used to store the frequency of each integer. We then iterate through this dictionary to find the largest lucky number.
This approach involves using an array to directly track the frequency of each integer. By using an array of fixed size, we can avoid using a hash map or dictionary, which optimizes space usage when the domain of the input elements is known.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), using a constant-size array.
1
public class Program {
public static int FindLucky(int[] arr) {
int[] freq = new int[501];
foreach (int num in arr) {
freq[num]++;
}
int maxLucky = -1;
for (int i = 1; i <= 500; i++) {
if (freq[i] == i && i > maxLucky) {
maxLucky = i;
}
}
return maxLucky;
}
public static void Main() {
int[] arr = { 2, 2, 3, 4 };
Console.WriteLine(FindLucky(arr));
}
}
This C# solution replaces the use of hash maps with a simple array, iterating through the array to find a value matching its frequency.