寻找第一个丢失的正数

版权声明:本文为博主原创文章,转载请注明出处。个人博客地址:https://yangyuanlin.club/ 欢迎来踩~~~~ https://blog.csdn.net/w7239/article/details/85224214

题目描述

  • First Missing Positive

Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.
Your algorithm should run in O(n) time and uses constant space.

思路

把正数n放在第n-1个位置上,这样从第一个位置开始,如果位置上的数不等于位置号,那么就是第一个缺失的正数。
while 是把数字一直换到正确的位置上为止。
对于每个数 A[ i ] 调整到 i - 1 位置,当然调整后还要接着判断。
最后从头扫一遍,发现第一个A[ i ] != i+1位置的就返回 i+1;
while 先判断前面语句,前者不满足并不读取后面的语句。

代码

#include<iostream>
using namespace std;

int firstMissingPositive(int A[], int n)
{
    for(int i=0; i<n; i++)
    {
        // 把数字一直换到正确的位置上为止
        while(A[i]>0 && A[i]<n && A[i]!=A[A[i]-1])
        {
            swap(A[i], A[A[i]-1]);
        }
    }

    // 最后从头扫一遍,发现第一个A[ i ] != i+1位置的就返回 i+1
    for(int j=0; j<n; j++)
    {
        if(A[j] != j+1)
            return j+1;
    }
    return n+1;
}

int main()
{
    int A[] = {1, 2, 0};
    cout << firstMissingPositive(A, 3) << endl;
    int B[] = {3,4,-1,1};
    cout << firstMissingPositive(B, 4) << endl;
    return 0;
}
  • 以上。

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


加粗样式

猜你喜欢

转载自blog.csdn.net/w7239/article/details/85224214