题解 | #缺失的第一个正整数#

缺失的第一个正整数

http://www.nowcoder.com/practice/50ec6a5b0e4e45348544348278cdcee5

原地哈希,利用下标值作为哈希的一部分

class Solution:
    def minNumberDisappeared(self , nums: List[int]) -> int:
        # write code here
        # 原地哈希
        res = -1
        if not nums:
            return 1
        len_nums = len(nums)
        # 先遍历数组将所有小于0的元素都改成n + 1
        for i in range(len_nums):
            if nums[i] < 0:
                nums[i] = len_nums + 1
        for i in range(len_nums):
            temp = abs(nums[i])
            if temp > 0 and temp <= len_nums:
                nums[temp - 1] = - abs(nums[temp - 1])
        for i in range(len_nums):
            if nums[i] > 0:
                res = i + 1
                break
        if i == len_nums - 1 and res == -1:
            res = len_nums + 1
        return res
全部评论

相关推荐

不愿透露姓名的神秘牛友
09-17 15:52
点赞 评论 收藏
分享
no_work_no...:大专三年最辛苦的应该是手机和电脑了吧
点赞 评论 收藏
分享
牛客83265014...:完了,连现在都没开始面,13号投的是不是晚了
秋招的第一个offer,...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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