My accepted java solution. Any better idea?


  • 0
    E
    public class Solution {
        public int firstMissingPositive(int[] A) {
            int i= 0;
            int len = A.length;
            while(i< len){
                while(A[i] != i+1){
                    if(A[i] <= 0 || A[i] > len || A[i] == A[A[i]-1])
                        break;
                    int tmp = A[A[i]-1];
                    A[A[i]-1] = A[i];
                    A[i] = tmp;
                }
                i++;
            }
            for (i = 0 ; i< len; i++){
                if(A[i]!= i+1)
                    break;
            }
            return i+1;
        }
    }
    

    Try to move all the number so that number i will be moved to A[i-1]. A[i] == A[A[i]-1] is made to make sure we dont fall into a loop


Log in to reply
 

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