4 lines of code to AC, O(n) complexity

  • -21
    class Solution {
        int firstMissingPositive(int A[], int n) {
            vector<bool> flg(n+1, false);
            for(int i=0; i<n; i++) if(A[i]>0&&A[i]<=n) flg[A[i]]=true;
            for(int i=1; i<=n; i++) if(!flg[i]) return i;
            return n+1;

  • 2

    Sorry, your algorithm's space complexity is not constant, but O(n). This algorithm is more hard if you solve it using constant space complexity.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.