> For the complete documentation index, see [llms.txt](https://imhuay.gitbook.io/studies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/niu-ke-0030-zhong-deng-que-shi-de-di-yi-ge-zheng-zheng-shu.md).

# 缺失的第一个正整数

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E4%B8%AD%E7%AD%89\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/pages/R5NyOzkn3qAZy7wCx1pS#中等) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E6%95%B0%E7%BB%84/%E7%9F%A9%E9%98%B5\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/pages/R5NyOzkn3qAZy7wCx1pS#数组矩阵)

**问题简述**

```
给定一个无重复元素的整数数组nums，请你找出其中没有出现的最小的正整数
要求：空间复杂度 O(1)，时间复杂度 O(n)
```

> [缺失的第一个正整数\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/50ec6a5b0e4e45348544348278cdcee5)

**思路**

* 利用数组下标记录出现过的正数

<details>

<summary><strong>写法1：先移除非正数</strong></summary>

```python
#
# 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
#
# 
# @param nums int整型一维数组 
# @return int整型
#
class Solution:
    def minNumberDisappeared(self , nums: List[int]) -> int:
        # write code here
        
        # 倒序移除所有非正数
        for i in range(len(nums) - 1, -1, -1):
            if nums[i] <= 0:
                nums.pop(i)
        
        # 利用数组下标这一隐含变量记录出现过的正数，避免使用额外空间
        N = len(nums)
        for x in nums:
            x = abs(x)
            if 0 < x <= N:
                nums[x - 1] = -abs(nums[x - 1])
        
        # 找到第一个非负数数，其下标就是没出现过的最小正数，如果没有，那么最小正数就是 N+1
        for i in range(N):
            if nums[i] > 0:
                return i + 1
        return N + 1
```

</details>

<details>

<summary><strong>写法2：修改非正数</strong></summary>

```python
#
# 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
#
# 
# @param nums int整型一维数组 
# @return int整型
#
class Solution:
    def minNumberDisappeared(self , nums: List[int]) -> int:
        # write code here
        
        N = len(nums)
        
        # 将所有非正数修改为 N+1
        for i in range(N):
            if nums[i] <= 0:
                nums[i] = N + 1
        
        # 利用数组下标这一隐含变量记录出现过的正数，避免使用额外空间
        for x in nums:
            x = abs(x)
            if 0 < x <= N:
                nums[x - 1] = -abs(nums[x - 1])
        
        # 找到第一个非负数数，其下标就是没出现过的最小正数，如果没有，那么最小正数就是 N+1
        for i in range(N):
            if nums[i] > 0:
                return i + 1
        return N + 1
```

</details>
