1. 程式人生 > >【LeetCode】961. N-Repeated Element in Size 2N Array 解題報告(Python & C+++)

【LeetCode】961. N-Repeated Element in Size 2N Array 解題報告(Python & C+++)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址:https://leetcode.com/problems/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:

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次,找出這個重複了N次的數字是什麼。

解題方法

字典

只要是和次數有關的題目,可以直接使用字典解決。這個題直接統計每個數字出現的次數,然後把次數等於N的返回即可。

python程式碼如下:

class Solution(object):
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        N = len(A) / 2
        count = collections.Counter(A)
        for k, v in count.
items(): if v == N: return k return 0

C++程式碼如下:

class Solution {
public:
    int repeatedNTimes(vector<int>& A) {
        const int N = A.size() / 2;
        unordered_map<int, int> m;
        for (int a : A) {
            m[a] ++;
        }
        for (auto x : m) {
            if (x.second == N) {
                return x.first;
            }
        }
        return 0;
    }
};

日期

2018 年 12 月 23 日 —— 周賽成績新高