Why change in swapping throws a Time Exceeded Error


  • 1
    G

    Here is my Code:

    public int firstMissingPositive(int[] A) {
        // Start typing your Java solution below
        // DO NOT write main() function
        for(int i=0; i < A.length; i++){
            while(A[i]>0 && A[i] <= A.length && A[i]!=i+1  &&  A[i]!=A[A[i]-1] ){
                int temp=A[A[i]-1];
                A[A[i]-1] = A[i];
                A[i]=temp;
            }
        }
        int index=0;
        while(index < A.length && A[index]==index+1) index++;
        return index+1;
    

    }

          When I change the swapping conditions as below :
                int temp=A[i];
                A[i]=A[A[i]-1];
                A[A[i]-1]=temp;
    

    My code throws a Time exceeded error . Any Idea why it is ?

    Thanks.


  • 4
    W

    I think this is actually one of the mistakes I made as well.
    The problem with

        int temp=A[i];
        A[i]=A[A[i]-1];
        A[A[i]-1]=temp;
    

    is that A[i] is modified on the second line and then used on the 3rd line.
    You can try using temp instead of A[i] on the 3rd line.


Log in to reply
 

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