LeetCode 41 - 缺失的第一个正数

本文解析LeetCode经典问题:如何在未排序整数数组中找到第一个缺失的正整数,要求时间复杂度为O(n)且空间复杂度为常数。提供了一种利用交换操作定位正确位置的解题思路,并通过实例演示和代码实现来深入讲解。
摘要由CSDN通过智能技术生成

题目链接icon-default.png?t=M276https://leetcode-cn.com/problems/first-missing-positive/

题目:

Given an unsorted integer array nums, return the smallest missing positive integer.

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

Example 1:

Input: nums = [1,2,0]
Output: 3


Example 2:

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


Example 3:

Input: nums = [7,8,9,11,12]
Output: 1


思路:

线性时间和常数空间确实是不小的要求,思维难度很大。一开始想到遍历一遍数组,对于某个数nums[i]都移动到nums[nums[i]-1]的位置(即下标的位置),然后再遍历一遍数组寻找不连续的地方即可。后来发现需要循环实现,每一次确定一个正确的位置。

最后判断的时候要注意边界条件(刚好是第一个或者len-1的时候缺失)

题解:

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int len=nums.size(), index=0;
        for(int i=0;i<len;i++){
            while(nums[i]>0 && nums[i]<=len && nums[i]!=nums[nums[i]-1]) swap(nums[nums[i]-1],nums[i]);
        }
        for(int i=0;i<len;i++){
            cout<<nums[i]<<" ";
        }/* checking the array */

        for(int i=0;i<len;i++){
            if(i==0 && nums[i]!=1) return 1;
            if(i!=len-1 && nums[i+1]!=nums[i]+1) return i+2;
        }
        return len+1;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值