961. N-Repeated Element in Size 2N Array

class Solution:
    def repeatedNTimes(self, A: List[int]) -> int:
        if len(A)&1 > 0:
            return -1
        aa = set(A)
        bb = {}
        for a in aa:
            bb[a] = 0
        for i in A:
            bb[i] += 1
            if bb[i]> 1 :
                result = i
                break
        return result

  60ms,14.1M

优化一:

class Solution:
    def repeatedNTimes(self, A: List[int]) -> int:
        return (sum(A)-sum(set(A)))//(len(A)//2-1)

  56ms,13.8M

优化二:

class Solution:
    def repeatedNTimes(self, A: List[int]) -> int:
        for i in A:
            if A.count(i)>1:
                return i
        return -1

  52ms,14.3M

原文地址:https://www.cnblogs.com/accumulationbystep/p/10430443.html