[leetcode] First Missing Positive

First Missing Positive
使用原数组下标和数组元素进行映射的方法,找到第一个不对应的元素,返回其下标+1即可。

#include "iostream"
using namespace std;

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        
        if (A==NULL||n<1) {//数组为空
            return 1;
        }
        int cur=0;
        
        while (cur<n) {
            
            int temp=A[cur];
            
            if (temp>0&&temp<=n&&A[temp-1]!=temp) {//注意交换条件
                //条件1:0<temp<=n
                //条件2:temp!=cur+1,条件3已经包含了这种情况temp=A[cur+1],故可以省去。
                //条件3:A[temp-1]!=temp,防止死循环
                //交换
                
                A[cur]=A[temp-1];
                A[temp-1]=temp;
                continue; //继续while循环
            }
            
            ++cur;
            
        }
        
        //遍历数组找到第一个映射不一致的位置
        
        cur=0;
        while (cur<n&&A[cur]==cur+1) {
            ++cur;//相对于cur++,推荐使用++cur

        }
        return cur+1;
    }
    
};

int main(){
    int A[]={3,4,-1,1};
    Solution so;
    cout<<so.firstMissingPositive(A, 4)<<endl;
    return 0;
}

精简代码版:

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        //[0..i) is 1..i
        for (int i=0; i<n; ) {
            if (A[i]==i+1) {
                ++i;
            }else if ((A[i]<=i)||(A[i]>n)||(A[A[i]-1]==A[i])){
                A[i]=A[--n];
            }else{
                swap(A[i], A[A[i]-1]);
            }
        }
        return n+1;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值