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).
1import java.util.HashMap;
2
3public class Main {
4 public static int findLucky(int[] arr) {
5 HashMap<Integer, Integer> freq = new HashMap<>();
6 for (int num : arr) {
7 freq.put(num, freq.getOrDefault(num, 0) + 1);
8 }
9 int maxLucky = -1;
10 for (int num : freq.keySet()) {
11 if (num == freq.get(num) && num > maxLucky) {
12 maxLucky = num;
13 }
14 }
15 return maxLucky;
16 }
17
18 public static void main(String[] args) {
19 int[] arr = {1, 2, 2, 3, 3, 3};
20 System.out.println(findLucky(arr));
21 }
22}
This Java solution uses a HashMap to track the frequency of each number in the array. Post the frequency count, it checks for the largest lucky number whose frequency equals 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.
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.