leetcode 268. 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?

复制代码
class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        n = len(nums)
        for i in range(0, n):
            if nums[i] != i:
                return i
        return n
复制代码

自己写排序的话:

复制代码
class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # [3,0,1]
        # 3 != nums[3-1], swap, [1, 0, 3]
        # 1 == nums[1-1]
        # 0 pass
        # 3 == nums[3-1] 
        # [9,6,4,2,3,5,7,0,1]
        for i in xrange(0, len(nums)):            
            while nums[i] != 0 and nums[i] != nums[nums[i]-1]:
                nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]               
        for i in xrange(0, len(nums)):
            if nums[i] != i+1:
                return i+1
        return 0        
复制代码

对于1~n的数字排序,直接O(n)可以搞定哇!

利用数学知识搞定:

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        return n*(n+1)/2-sum(nums)        

 

复制代码
class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        xor = len(nums)
        for i,n in enumerate(nums):
            xor = xor^n^i
        return xor
复制代码

 

还有使用二分搞定:

复制代码
class Solution {
    // Binary Search
    public int missingNumber(int[] nums) { //binary search
        Arrays.sort(nums);
        int left = 0, right = nums.length, mid= (left + right)/2;
        while(left<right){
            mid = (left + right)/2;
            if(nums[mid]>mid) right = mid;
            else left = mid+1;
        }
        return left;
    }

}
复制代码

 

posted @   bonelee  阅读(219)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示