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).
1using System;
2using System.Collections.Generic;
3
4public class Program {
5 public static int FindLucky(int[] arr) {
6 Dictionary<int, int> freq = new Dictionary<int, int>();
7 foreach (int num in arr) {
8 if (freq.ContainsKey(num)) {
9 freq[num]++;
10 } else {
11 freq[num] = 1;
12 }
13 }
14 int maxLucky = -1;
15 foreach (var kvp in freq) {
16 if (kvp.Key == kvp.Value && kvp.Key > maxLucky) {
17 maxLucky = kvp.Key;
18 }
19 }
20 return maxLucky;
21 }
22
23 public static void Main() {
24 int[] arr = { 1, 2, 2, 3, 3, 3 };
25 Console.WriteLine(FindLucky(arr));
26 }
27}
This C# solution utilizes a dictionary to compute the frequency of each number in the array. After computing frequencies, it finds the largest lucky number by checking if the value equals its frequency.
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.