python-leetcode-961. 重複 N 次的元素

解法1:先排序,再比較相鄰的元素:

class Solution:
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        A.sort()
        for i in range(len(A) - 1):
            if A[i] == A[i + 1]:
                return A[i]

解法2:先排序,再比較 A[0] 與 A[N-1],有3種可能:

相等:x x x | a b c
不等:a b c | x x x
不等:a b x | x x c

class Solution:
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        A.sort()
        n = len(A) // 2
        return A[0] if A[0] == A[n-1] else A[n]

解法3:把數組看作一個環,則相隔兩個空位以內的數一定會出現重複值,例如:

x x a b (跟 axxb, abxx, xabx 等情況相同)
a x b x (跟 xaxb 相同)
也可以這樣理解,比如有三個數排成一圈,要往排列裏插入三個相同的數,相同的數相隔的 最小距離要麼是1,要麼是2:

a_b_c
^ ^ ^ ^

class Solution:
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        for i in range(len(A)):
            if A[i] == A[i-1] or A[i] == A[i-2]:
                return A[i]

解法四:根據題目分析可知,只會重複一個數字

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

解法五:hash

class Solution(object):
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        dict_cache = {}
        for item in A:
            if item in dict_cache:
                return item
            dict_cache[item]=1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章