题解 | #缺失数字#

缺失数字

http://www.nowcoder.com/practice/9ce534c8132b4e189fd3130519420cde

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 找缺失数字
# @param a int整型一维数组 给定的数字串
# @return int整型
#
class Solution:
    def solve(self , a ):
        # write code here
        start = 0
        end = len(a) - 1
        middle = (start + end)//2
        while (end - start) > 1:
            if a[middle] > (a[0] + middle):
                end = middle
            else:
                start = middle
            middle = (start + end)//2
        if((a[end] == (a[0]+end)) & (a[0]!=0)):
            return a[0] - 1
        elif((a[end] == (a[0]+end)) & (a[0]==0)):
            return a[end] + 1
        return a[end] -1
全部评论
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 找缺失数字 # @param a int整型一维数组 给定的数字串 # @return int整型 # class Solution: def solve(self , a ): # write code here start = 0 end = len(a) - 1 if((a[end] == (a[start]+end)) & (a[start]!=0)): return a[start] - 1 elif((a[end] == (a[start]+end)) & (a[start]==0)): return a[end] + 1 middle = (start + end)//2 while end > start: if a[middle] > (a[0] + middle): end = middle -1 else: start = middle + 1 middle = (start + end)//2 #a[end+1] 到 a[len(a)-1]是连续的,值为a[0]+end+1 到 a[0]+len(a),值比实际多1 #a[0]到a[start-1]是连续的,值为a[0] 到 a[0]+start-1,值是正确的,end比start多1,或相等 if(a[end] == (a[0] + end)): return a[end] + 1 return a[end] -1
点赞 回复 分享
发布于 2021-10-25 17:44
简单的二分查找,不过如果是一组连续的数字,如果不是从0开始就默认是缺失前面的数字,比如说[4,5,6]默认缺失3,如果是从0开始,就缺失后面的数字,比如说0,1,2,3缺失4
点赞 回复 分享
发布于 2021-10-25 09:59
题目:从 0,1,2,...,n 这 n+1 个数中选择 n 个数,选择出的数字依然保持有序,找出这 n 个数中缺失的那个数,要求 O(n) 或 O(log(n)) 并尽可能小。
点赞 回复 分享
发布于 2021-10-25 09:58

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务