961. N-Repeated Element in Size 2N Array
Description
You are given an integer array nums with the following properties:
nums.length == 2 * n.numscontainsn + 1unique elements.- Exactly one element of
numsis repeatedntimes.
Return the element that is repeated n times.
Example 1:
Input: nums = [1,2,3,3] Output: 3
Example 2:
Input: nums = [2,1,2,5,3,2] Output: 2
Example 3:
Input: nums = [5,1,5,2,5,3,5,4] Output: 5
Constraints:
2 <= n <= 5000nums.length == 2 * n0 <= nums[i] <= 104numscontainsn + 1unique elements and one of them is repeated exactlyntimes.
Solutions
Solution 1: Hash Table
Since the array \(\textit{nums}\) has a total of \(2n\) elements, with \(n + 1\) distinct elements, and one element repeated \(n\) times, this means the remaining \(n\) elements in the array are all distinct.
Therefore, we only need to iterate through the array \(\textit{nums}\) and use a hash table \(s\) to record the elements we've encountered. When we encounter an element \(x\), if \(x\) already exists in the hash table \(s\), it means \(x\) is the repeated element, and we can directly return \(x\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Solution 2: Mathematics
According to the problem description, half of the elements in the array \(\textit{nums}\) are the same. If we view the array as a circular arrangement, then there is at most \(1\) other element between two identical elements.
Therefore, we iterate through the array \(\textit{nums}\) starting from index \(2\). For each index \(i\), we compare \(\textit{nums}[i]\) with \(\textit{nums}[i - 1]\) and \(\textit{nums}[i - 2]\). If they are equal, we return that value.
If we don't find the repeated element in the above process, then the repeated element must be \(\textit{nums}[0]\), and we can directly return \(\textit{nums}[0]\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |