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).
1#include <stdio.h>
2
3int findLucky(int* arr, int arrSize) {
4 int freq[501] = {0};
5 for (int i = 0; i < arrSize; i++) {
6 freq[arr[i]]++;
7 }
8 int maxLucky = -1;
9 for (int i = 1; i <= 500; i++) {
10 if (freq[i] == i) {
11 if (i > maxLucky) maxLucky = i;
12 }
13 }
14 return maxLucky;
15}
16
17int main() {
18 int arr[] = {1, 2, 2, 3, 3, 3};
19 int arrSize = sizeof(arr) / sizeof(arr[0]);
20 printf("%d\n", findLucky(arr, arrSize));
21 return 0;
22}
In this C solution, we use an array freq
of size 501 to capture the frequency of numbers from 1 to 500. We then iterate over the original array updating our frequency array. Finally, we search for the maximum lucky number by checking if the frequency matches the number itself.
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.
1using System;
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.