【算法训练】剑指offer#53 - II 0~n-1中缺失的数字
一、描述
剑指 Offer 53 - II. 0~n-1中缺失的数字
一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
示例 1:
输入: [0,1,3]
输出: 2
示例 2:
输入: [0,1,2,3,4,5,6,7,9]
输出: 8
二、思路
- 从头遍历数组然后比较,看看超时么
class Solution:
def missingNumber(self, nums: List[int]) -> int:
judge_list = [i for i in range(len(nums))]
for i in nums:
judge_list[i] = -1
for i in judge_list:
if i < 0:
return i
- 啊.....下面逻辑写法了
class Solution:
def missingNumber(self, nums: List[int]) -> int:
judge_list = [i for i in range(len(nums)+1)]
for i in nums:
judge_list[i] = -1
for i in range(len(judge_list)):
if judge_list[i] > 0:
return i
- 这次问题出现在长度为1的数组上
- 不是,就是大于0不对,应该是大于-1
三、解题
class Solution:
def missingNumber(self, nums: List[int]) -> int:
judge_list = [i for i in range(len(nums)+1)]
for i in nums:
judge_list[i] = -1
for i in range(len(judge_list)):
if judge_list[i] > -1:
return i