題目難度:簡單
題目描述:一個長度爲n-1的遞增排序數組中的所有數字都是唯一的,並且每個數字都在範圍0~n-1之內。在範圍0~n-1內的n個數字中有且只有一個數字不在該數組中,請找出這個數字。
實例如下:
這道題我自己開始的分析:
我將其分爲三種情況進行考慮:
a.當數組缺失的是數值0,即爲第一個元素缺失;
b.當數組中缺少中間值;
c.當數組中缺少最大值,即最末位的元素
代碼如下:
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ # 情況1:第一位元素缺失 if len(nums) == 1 & nums[0] == 1: return 0 # 情況二:中間值缺失 for i in range(len(nums)): if nums[i] != i: return i # 情況三,末尾元素缺失 num_list = [int(x) for x in nums] return num_list[len(num_list) - 1] + 1
執行結果如下:
雖然是一道簡單題目,但是做完後,我發現,嗯,有沒有那種套路啥的,或者更好的做法,於是乎,我想到了二分法,思路如下:
解題思路:
a.排序數組中的搜索問題,首先一定要想到二分法
b.本題,我們按照題目意思來看,數組可以按照以下規則劃分爲兩個部分:
1.左子數組:nums[i]=i
2.右子數組:nums[i]≠i
c.缺失的數字等於“右子數組的首位元素”對應的索引;因此考慮使用二分法查找“右子數組的首位元素”
代碼如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # @Time : 2020/6/2 10:03 # @Author : ZFJ # @File : 缺失的數字.py # @Software: PyCharm """ class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ i = 0 j = len(nums) - 1 while i <= j: m = (i + j) // 2 if nums[m] == m: i = m + 1 else: j = m - 1 return i