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

缺失的第一个正整数

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
全部评论

相关推荐

那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
牛客38347925...:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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