leetcode41. First Missing Positive

 

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

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

Example 2:

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

Example 3:

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

Note:

Your algorithm should run in O(n) time and uses constant extra space.


Seen this question in a real interview before?  

Yes

No

Wont work for {6, 3, 4, 1, 8, 2}. Your solution assumes that highest integer is less than n.

Why does it not work? In the while loop, one of the conditions is A[i] <= n, so in this case, 8 won't move, because it's larger than the length. So after the for loop, your array becomes [1,2,3,4,8,6], and 8 != 4+1, so 5 should be returned. Hope this helps.

 

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int i = 0;
        int n = nums.size();
        while (i < n)
        {
            if (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i])
                swap(nums[i], nums[nums[i]-1]);
            else
                i++;
        }
        for (i = 0; i < n; ++i)
            if (nums[i] != (i+1))
                return i+1;
        return n+1;
    }
};

 

 

反思

负数和超限值在交换过程中可以进行操作,当要对他们进行nums[nums[i] - 1] != nums[i]这种比较的时候就可以跳过了,让他们站着当前位置,

一来知道缺失哪些值,而来可以根据比较,因为已经把各个位置的数还原了(其实就是相当于排序),只要在n内,不等就知道该位置缺失了

那么这个本来的数就是i+1正整数的原因。

这种交换位置,把各个数安排在本应该在的位置方法经常用到,对于负数和nums[i]>nums.size()这两个坑处理的非常好

另外 find的用法我有时候也没搞清

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值