LeetCode //C - 41. First Missing Positive

本文介绍了一个在给定未排序整数数组中找到第一个缺失的正整数的算法。该算法在O(n)时间复杂度和O(1)辅助空间内运行,通过分离负数和零,以及对数组进行调整来确定答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

41. First Missing Positive

Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums.

You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
 

Example 1:

Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.

Example 2:

Input: nums = [3,4,-1,1]
Output: 2

Explanation: 1 is in the array but 2 is missing.

Example 3:

Input: nums = [7,8,9,11,12]
Output: 1
Explanation: The smallest positive integer 1 is missing.

Constraints:
  • 1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
  • − 2 31 < = n u m s [ i ] < = 2 31 − 1 -2^{31} <= nums[i] <= 2^{31} - 1 231<=nums[i]<=2311

From: LeetCode
Link: 41. First Missing Positive


Solution:

Ideas:
  1. First, separate negative numbers and zeros from positive numbers because we’re only interested in the smallest positive missing integer. We can ignore numbers that are outside the range [1, numsSize] since the smallest missing positive integer must be within this range or just outside it (numsSize + 1).

  2. Next, we iterate through the array, and for each positive integer nums[i] that is within the range [1, numsSize], we swap nums[i] with nums[nums[i] - 1] (the position it should be in). We repeat this process until all integers are in their correct positions or if swapping no longer changes the array.

  3. Finally, we scan the array again. The first index i for which nums[i] != i + 1 indicates that i + 1 is the smallest missing positive integer. If all numbers are in their correct positions, the smallest missing positive integer is numsSize + 1.

Code:
int firstMissingPositive(int* nums, int numsSize) {
    for (int i = 0; i < numsSize; ++i) {
        while (nums[i] > 0 && nums[i] <= numsSize && nums[nums[i] - 1] != nums[i]) {
            // Swap nums[i] with nums[nums[i] - 1]
            int temp = nums[nums[i] - 1];
            nums[nums[i] - 1] = nums[i];
            nums[i] = temp;
        }
    }

    for (int i = 0; i < numsSize; ++i) {
        if (nums[i] != i + 1) {
            return i + 1; // Found the first missing positive
        }
    }

    return numsSize + 1; // All positive numbers [1, numsSize] are present
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值