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
题目理解:
给定一个数组,数组中有2N个数,其中有N个数只在数组中出现了一次,有一个数在数组中出现了N次,找出这个重复出现了N次的数
解题思路:
将数组排序,出现在N位置的数一定是重复了N次的数。只有一种特殊情况,即0 ~ N-1位置的数是只出现了一次的数,N ~ 2N-1位置的数是重复了N次的数,处理的方法是判断A[0]与A[1]是否相等,相等则返回A[0]
class Solution {
public int repeatedNTimes(int[] A) {
Arrays.sort(A);
if(A[0] == A[1])
return A[0];
int len = A.length;
return A[len / 2];
}
}