【Leetcode】268 Missing Number


更新于2019.6.17 22:56

题目描述

题目含义是,假设有一个长度为n+1的数组(其取值为[0,1,2,...,n]),随机拿掉一个数,使之变为长为n的array,打乱顺序问拿掉的数是几?
image


t i m e : O ( n l o g n ) ; s p a c e : O ( 1 ) time:O(nlogn);space:O(1) time:O(nlogn);space:O(1)

想法是如果先排序,那么遍历的时候会很容易判断前后两个数是否差值为1。这个好像能补上上次缺的方法。

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        if nums[-1]!=len(nums): #ensure not loss final num
            return len(nums)
        if nums[0] != 0:    #ensure not loss first num
            return  0
        for i in range(1,len(nums)):
            if nums[i-1]+1 != nums[i]:  #if integer not obey this func, means something wrong.
                # print(nums[i-1]+1)
                return nums[i-1]+1

S = Solution()
# nums = [3,0,1]
nums = [9,6,4,2,3,5,7,0,1]
S.missingNumber(nums)

Runtime: 136 ms, faster than 28.83% of Python online submissions for Missing Number.
Memory Usage: 12.7 MB, less than 79.39% of Python online submissions for Missing Number.


t i m e : O ( n ) ; s p a c e : O ( n ) time:O(n);space:O(n) time:O(n);space:O(n)
		nums = set(nums)	#python中set的空间开销为$O(n)$
        for i in range(len(nums)+1):
            if i not in nums:
                # print(i)
                return i

Runtime: 116 ms, faster than 72.13% of Python online submissions for Missing Number.
Memory Usage: 13.3 MB, less than 6.49% of Python online submissions for Missing Number.

t i m e : O ( n ) ; s p a c e : O ( 1 ) time:O(n);space:O(1) time:O(n);space:O(1)

这个方法就比较机灵了,利用高斯累加和减去所有值之和即可得到最终值

		tmp = 0
        L = len(nums)
        summation = L*(L+1)//2
        print(summation)
        for i in range(L):
            tmp = tmp + nums[i]
            # print(tmp)
        # print(summation-tmp)
        return summation-tmp

Runtime: 108 ms, faster than 85.34% of Python online submissions for Missing Number.
Memory Usage: 12.9 MB, less than 29.26% of Python online submissions for Missing Number.


t i m e : O ( ) ; s p a c e : O ( ) time:O();space:O() time:O();space:O()

最后一种之前没接触过,其实就是位运算,拿数组下标与对应的值做或运算,根据相同为0,不同为1的运算规则,得到1时即可判断缺失值。我好像想的太简单了,一下子卡住了...


参考:Leetcode268

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值