Algorithm :Missing Number

2017-11-12  本文已影响11人  singmiya

Q: Missing Number

Description:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

A1: Bit Manipulation

Intuition
We can harness the fact that XOR is its own inverse to find the missing element in linear time.

Algorithm
Because we know that nums containsnnumbers and that it is missing exactly one number on the range [0..n-1] , we know thatndefinitely replaces the missing number in nums. Therefore, if we initialize an integer tonand XOR it with every index and value, we will be left with the missing number. Consider the following example (the values have been sorted for intuitive convenience, but need not be):

Index 0 1 2 3
Value 0 1 3 4
WX20171111-150701@2x

Python3

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

Complexity Analysis

A2:Gauss' Formula

Intuition
One of the most well-known stories in mathematics is of a young Gauss, forced to find the sum of the first 100 natural numbers by a lazy teacher. Rather than add the numbers by hand, he deduced a closed-form expression for the sum, or so the story goes. You can see the formula below:

QQ20171112-092718@2x.png

Algorithm

We can compute the sum of nums in linear time, and by Gauss' formula, we can compute the sum of the first n natural numbers in constant time. Therefore, the number that is missing is simply the result of Gauss' formula minus the sum of nums, as nums consists of the first n natural numbers minus some number.

Python3

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

Complexity Analysis

上一篇 下一篇

猜你喜欢

热点阅读