1. 程式人生 > >LeetCode268:Missing Number(多種方法)

LeetCode268:Missing Number(多種方法)

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?


LeetCode:連結

第一種:先排序,首先可以判斷第一個數是不是0,如果不是,說明丟失的數字是0,然後可以判斷最後一個數字是不是陣列的長度,如果不是,說明丟失的陣列是陣列的長度。然後遍歷判斷哪個數丟失,正常的陣列應該都是逐漸+1的,讓它和陣列比較,不相等的那個就是丟失的。時間複雜度O(nlogn),空間複雜度O(1)

class Solution:
    def missingNumber(self, nums):
        nums.sort()

        # Ensure that n is at the last index
        if nums[-1] != len(nums):
            return len(nums)
        # Ensure that 0 is at the first index
        elif nums[0] != 0:
            return 0

        # If we get here, then the missing number is on the range (0, n)
        for i in range(1, len(nums)):
            expected_num = nums[i-1] + 1
            if nums[i] != expected_num:
                return expected_num

第二種:必須是hashset,因為查詢很快。遍歷0到n,哪個數字不在陣列中,哪個就是丟失的。一定要用hashset判斷,因為查詢的時候是常數時間。時間複雜度O(n),空間複雜度O(n)。

class Solution:
    def missingNumber(self, nums):
        num_set = set(nums)
        n = len(nums) + 1
        for number in range(n):
            if number not in num_set:
                return number

第三種:異或判斷的方法。比如一個數組是0,1,3,消失的數字是2,然後用序列號和值去異或,再和陣列的長度異或,其他的數字都是兩兩成對的,所以異或之後都為0,0和A異或還是A,最終把A找到。時間複雜度是O(n),空間複雜度是O(1)。

class Solution:
    def missingNumber(self, nums):
        missing = len(nums)
        for i, num in enumerate(nums):
            missing ^= i ^ num
        return missing

第四種:高斯公式。首項加末項乘以項數除以2是正常的和,然後算陣列加起來的和,相減就是沒有的那個數。高斯公式的時間複雜度是O(1),但是加和的時間複雜度是O(n),所以最終時間複雜度是O(n),空間複雜度是O(1)。

class Solution:
    def missingNumber(self, nums):
        expected_sum = len(nums)*(len(nums)+1)//2
        actual_sum = sum(nums)
        return expected_sum - actual_sum