zoukankan      html  css  js  c++  java
  • 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;
        }
    
    }
  • 相关阅读:
    文件编程---库函数
    linux文件编程----系统调用
    makefile工程管理
    快速上手日期插件laydate
    js判断浏览器类型以及语言
    谷歌支付服务端详细讲解(PHP)
    php中的date和strtotime函数妙用
    本地搭建GitLab
    mysql查询语句常用字段操作函数
    php中签名公钥、私钥(SHA1withRSA签名)以及AES(AES/ECB/PKCS5Padding)加密解密详解
  • 原文地址:https://www.cnblogs.com/bonelee/p/8698308.html
Copyright © 2011-2022 走看看