1. 程式人生 > >劍指offer Python版 - 陣列中重複的數字

劍指offer Python版 - 陣列中重複的數字


題目描述

在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 陣列中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出陣列中任意一個重複的數字。 例如,如果輸入長度為7的陣列{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。


方法1:

先把輸入的陣列排序,再從頭到尾掃描排序後的陣列,如果相鄰的兩個元素相等,則存在重複數字。時間複雜度O(nlogn).

# -*- coding:utf-8 -*-
class Solution:
    # 這裡要特別注意~找到任意重複的一個值並賦值到duplication[0]
    # 函式返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        numbers = sorted(numbers)
        for i in range(1, len(numbers)):
            if numbers[i] == numbers[i - 1]:
                duplication[0] = numbers[i]
                return True
        return False

執行時間:22ms

佔用記憶體:5836k


方法2:

利用雜湊表來解決。從頭到尾掃描陣列的每個元素,每掃描到一個元素,都可以用O(1)的時間來判斷雜湊表中是否已經存在該數字,如果存在,說明找到了重複元素,如果不存在,則將其加入到雜湊表中。時間複雜度O(n),空間複雜度O(n)。
# -*- coding:utf-8 -*-
class Solution:
    # 這裡要特別注意~找到任意重複的一個值並賦值到duplication[0]
    # 函式返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        hash_table = [None] * len(numbers)
        for i in range(len(numbers)):
            hash_value = numbers[i]
            if hash_table[hash_value]:
                duplication[0] = hash_value
                return True
            else:
                hash_table[hash_value] = hash_value
        return False

執行時間:29ms

佔用記憶體:5736k


方法3:

由於陣列中元素都在0~n - 1的範圍內,如果這個陣列中沒有重複元素,那麼當陣列排序後,數字i將會處於i的位置。從頭到尾依次掃描陣列中的元素,當掃描第i個元素時,如果這個元素是i,則繼續掃描下一個元素,如果不是i,而是m,則將其與第m個元素比較,如果兩者相等,則找到了重複的數字,如果不相等,則將二者交換位置,重複該過程,直到找到重複元素。時間複雜度O(n),空間複雜度O(1).
# -*- coding:utf-8 -*-
class Solution:
    # 這裡要特別注意~找到任意重複的一個值並賦值到duplication[0]
    # 函式返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        for i in range(len(numbers)):
            while numbers[i] != i:
                if numbers[numbers[i]] == numbers[i]:
                    duplication[0] = numbers[i]
                    return True
                else:
                    numbers[numbers[i]], numbers[i] = numbers[i], numbers[numbers[i]]
        return False

執行時間:23ms

佔用記憶體:5732k


注:執行結果資料來自牛客網。