1. 程式人生 > 其它 >leetcode 961. N-Repeated Element in Size 2N Array(python)

leetcode 961. N-Repeated Element in Size 2N Array(python)

技術標籤:leetcodeleetcode

描述

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

解析

根據題意,只需要找出在 A 中出現次數最多的那個元素即可,使用內建的 Counter 統計之後即可找出答案。

解答

class Solution(object):
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        r = collections.Counter(A).most_common(1)
        return r[0][0]

執行結果

Runtime: 204 ms, faster than 22.88% of Python online submissions for N-Repeated Element in Size 2N Array.
Memory Usage: 14.7 MB, less than 48.33% of Python online submissions for N-Repeated Element in Size 2N Array.

解析

根據題意,只需要找出在 A 中出現次數最多的那個元素即可,定義一個集合 a ,在遍歷 A 的過程中,只要沒有在 a 中出現就新增到 a ,如果出現過直接返回改元素即可。

解答

class Solution(object):
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        a = set()
        for i in A:
            if i in a:
                return i
            a.add(i)
        return 

執行結果

Runtime: 160 ms, faster than 88.95% of Python online submissions for N-Repeated Element in Size 2N Array.
Memory Usage: 14.2 MB, less than 92.55% of Python online submissions for N-Repeated Element in Size 2N Array.

原題連結:https://leetcode.com/problems/n-repeated-element-in-size-2n-array/