[leetcode] first missing positive

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.

这个题目不是我自己的思路 T T,想法太tricky了。。。

先把负的搞成大的,然后用bitmap的方法来换嘛~~然后把bitmap的0 or 1记在原来的符号上面,酱紫就可以省空间啦~ 

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        for(int i = 0; i < n; i++){
            if(A[i] <= 0) A[i] = n + 2;
        }
        
        int tmp;
        for(int i = 0; i < n; i++){
            tmp = abs(A[i]);
            if(tmp -1 < n){
                A[tmp - 1] = -1 * abs(A[tmp - 1]);
            }
        }
        for(int i = 0; i < n; i++){
            if(A[i] > 0) return i + 1;
        }
        return n+1;
    }
};


你可能感兴趣的:(LeetCode)