961. N-Repeated Element in Size 2N Array
In a array A
of size 2N
, there are N+1
unique elements, and exactly one of these elements is repeated N times.
Return the element repeated N
times.
Example 1:
Example 2:
Example 3:
解题要点:
遍历整个数组,当找到有相同数时,返回这个数。
学习解法:
Compare
If we ever find a repeated element, it must be the answer. Let's call this answer the major element.
Consider all subarrays of length 4. There must be a major element in at least one such subarray.
This is because either:
There is a major element in a length 2 subarray, or;
Every length 2 subarray has exactly 1 major element, which means that a length 4 subarray that begins at a major element will have 2 major elements.
Thus, we only have to compare elements with their neighbors that are distance 1, 2, or 3 away.
Complexity Analysis
Time Complexity: O(N), where N is the length of
A
.Space Complexity: O(1).
Last updated
Was this helpful?