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
Similar to our first C solution but highlighting direct array access instead of hash maps, this implementation calculates frequency using a fixed-size array from 1 to 500. The result is determined by comparing each index with its frequency count directly.