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:
Input: [1,2,3,3]
Output: 3
Example 2:
Input: [2,1,2,5,3,2]
Output: 2
Example 3:
Input: [5,1,5,2,5,3,5,4]
Output: 5
Note:
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length
is even
Solution: Randomization
Randomly pick two numbers in the array, if they are the same (25% probability) return the number, do it until the two numbers are the same.
Time complexity: O(1) expected 4
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua, running time: 72 ms class Solution { public: int repeatedNTimes(vector<int>& A) { int i = 0; int j = 0; while (i == j || A[i] != A[j]) { i = rand() % A.size(); j = rand() % A.size(); } return A[i]; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment