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

Easy

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

题目大意:在一个大小为2N的数组中,包含N+1个不同的数字,其中有一个数字重复N次,找出这个多次重复的数字。

提示:

1.数组长度为0~10000

2.数字大小为大于等于0,小于10000

3.数组的长度为偶数

由题目可知,数组中除了那个重复N次的数字以外,其他数字都是各不相同的,因此只要判断出哪个数字重复,那么这个数字就是目标数字。

可以使用无序集合unordered_set对出现的数字进行记录,只要数字不是第一次出现,那么它就是目标数字。

代码如下:

class Solution {
public:
    int repeatedNTimes(vector<int>& A) {
        unordered_set<int> nums;
        for(int num : A){
            if(nums.count(num) != 0){
                return num;
            }
            nums.insert(num);
        }
        return 0;
    }
};
原文地址:https://www.cnblogs.com/cff2121/p/11421127.html