Sponsored
Sponsored
This approach uses a hashmap (or dictionary) to store the count of each element in the array. By iterating through the array and updating the map, we can easily identify the element that repeats n
times by checking the count value.
Time Complexity: O(N), where N is the length of the nums array because we iterate over it once.
Space Complexity: O(1), since the hashmap is of a fixed size of 10001.
1using System;
2using System.Collections.Generic;
3
4class Solution {
5 public int RepeatedNTimes(int[] nums) {
6 Dictionary<int, int> map = new Dictionary<int, int>();
7 foreach (int num in nums) {
8 if (map.ContainsKey(num)) map[num]++;
9 else map[num] = 1;
10
11 if (map[num] > 1) return num;
12 }
13 return -1;
14 }
15 static void Main() {
16 Solution sol = new Solution();
17 Console.WriteLine(sol.RepeatedNTimes(new int[] { 1, 2, 3, 3 }));
18 }
19}
20
The C# solution employs a Dictionary
to count the appearance of each number, returning the first with a count exceeding one.
In this method, we first sort the array. If an element is repeated n
times and the rest are unique, the repeated element must be at the center of the sorted array, appearing consecutively. Checking the middle indexes should reveal the repeated element.
Time Complexity: O(N log N), due to the sorting process.
Space Complexity: O(1) in place sorting.
1
Python's solution leverages the built-in sort()
, making it simple to identify the repeated number immediately after sorting.