Leetcode 961. N-Repeated Element in Size 2N Array

Problem:

 

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:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A.length is even

 

Solution:

  这道题是首个我写入博客的easy题,因为这道题的解法思路太巧妙了,计数的做法就不说了,主要来讲线性时间复杂度和常量空间复杂度的解法。这道题和摩尔筛选法不同,摩尔筛选法适用于重复数字大于数组长度一半的情况,这里是等于。这道题有一个隐藏规律,我们只要找出一对重复的数字就行了,并且至少存在一个长度为4的子数组里存在一对重复的数字。如果说数组长度非常长,那么最大的相同数字间的最小间隔为2,比如{0,1,0,2,0,3,0,4...},之所以为3(即长度为4的子数组存在重复数字)是因为要考虑特殊情况如{0,1,2,0}。

Code:

 

 1 class Solution {
 2 public:
 3     int repeatedNTimes(vector<int>& A) {
 4         for (int k = 1; k <= 3; ++k)
 5             for (int i = 0; i < A.size() - k; ++i)
 6                 if (A[i] == A[i+k])
 7                     return A[i];
 8         return -1;
 9     }
10 };

 

posted on 2019-02-21 14:15  周浩炜  阅读(252)  评论(0编辑  收藏  举报

导航