乱序中找出第一次未出现的正整数

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

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

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

寻找数组中第一个未出现的正整数,题目本身比较常见,关键在于题目要求只能使用常数额外空间。

A:

虽然不能再另外开辟非常数级的额外空间,但是可以在输入数组上就地进行swap操作。

思路:交换数组元素,使得数组中第i位存放数值(i+1)。最后遍历数组,寻找第一个不符合此要求的元素,返回其下标。整个过程需要遍历两次数组,复杂度为O(n)

下图以题目中给出的第二个例子为例,讲解操作过程。

最后,具体实现如下:

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        
        // 通过交换  使得 下标i位置 放i+1的数值
        int i=0;
        int n=nums.size();
        while(i<n){
            if((i+1)!=nums[i]&&nums[i]>=1&&nums[i]<=n&&nums[nums[i]-1]!=nums[i]){
                swap(nums[i],nums[nums[i]-1]);
            }else{
                i++;
            }
        }
        
        for(int i=0;i<n;++i){
            if(nums[i]!=(i+1)){
                return i+1;
            }
        }
        return n+1;
    }
};

复制代码
 1 class Solution {
 2 public:
 3     int firstMissingPositive(int A[], int n) {
 4         int i = 0;
 5         while (i < n)
 6         {
 7             if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i])
 8                 swap(A[i], A[A[i]-1]);
 9             else
10                 i++;
11         }
12         for (i = 0; i < n; ++i)
13             if (A[i] != (i+1))
14                 return i+1;
15         return n+1;
16     }
17 };
复制代码

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/80490705