LeetCode 41. First Missing Positive

1. 题目要求

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.

2. 解题思路

处理这类问题, 一个基本的思路就是, 先对这个数据序列进行排序, 然后找到所缺少的那个值。 但是基于比较的排序的时间复杂度最好的一般都是 O(nlogn) 的了。而这里要求使用 O(n) 的时间复杂度, 一般可以想到的是借助一个hash 表来进行 处理, 用空间换取时间。可是这样的话, 他的空间复杂度又是不符合要求的了, 空间复杂度为 O(n) , 与我们所需要的常量空间复杂度还有一段距离, 怎么办呢, 我们想到了直接借助原来的数组, 通过将原数组中的值放置到他的相应位置上, 实现数组的排序工作~~
突然发现自己好机智

3. code

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

                swap(nums[i], nums[nums[i] - 1]);
                continue;
            }
            i++;
        }

        int target = 1;
        for (int i = 0; i < n; i++){
            if (target != nums[i])
                break;
            else
                target++;
        }
        return target;
    }
};



class Solution1 {
public:
    int firstMissingPositive(vector<int>& nums) {
        unordered_set<int> myset(nums.begin(), nums.end());
        for (int i = 1; i != nums.size() + 1; i++){
            if (myset.count(i) == 0)
            return i;
        }
        return nums.size() + 1;
    }
};

4. 大神解法

和我们的思路是一致的

/* Put each number in its right place. For example: When we find 5, then swap it with A[4]. At last, the first place where its number is not right, return the place + 1. */
class Solution
{
public:
    int firstMissingPositive(int A[], int n)
    {
        for(int i = 0; i < n; ++ i)
            while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
                swap(A[i], A[A[i] - 1]);

        for(int i = 0; i < n; ++ i)
            if(A[i] != i + 1)
                return i + 1;

        return n + 1;
    }
};

你可能感兴趣的:(LeetCode)