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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」