LeetCode 41 - 缺失的第一个正数

题目链接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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值