268. Missing Number

来源:互联网 发布:最新中英文翻译软件 编辑:程序博客网 时间:2024/06/05 06:22

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?

My code:

    def missingNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        n = len(nums)+1        return  n*(n-1)/2 -sum(nums)
overflow
    def missingNumber(self, nums):        nums.sort()        for i in range (0,len(nums)):            if nums[i]^ i !=0:                return i        return 0
https://discuss.leetcode.com/topic/23427/3-different-ideas-xor-sum-binary-search-java-code/2
    def missingNumber(self, nums):        nums.sort()        left = 0        right = len(nums)        mid = (left+right)/2        while left<right:            mid = (left+right)/2            if (nums[mid]>mid):                right = mid            else:                left = mid +1        return left




0 0