[First missing positive]Why my answer is wrong?


  • 0
    M

    I run my code. The answer I got is the same with the except output and the running time is not exceed. But my answer is not accept. Could anybody have any idea?

    PS: this is my solution:

    public class Solution {
    /**    
     * @param A: an array of integers
     * @return: an integer
     */
    public int firstMissingPositive(int[] A) {
        // write your code here  
        if(A == null || A.length == 0){
            return 1;
        }
        for(int i = 0; i < A.length; i++){
            if(A[i] <= 0 || A[i] > A.length){
                break;
            }
            
            if(A[i] != i + 1){
                int temp = A[i];
                A[i] = A[temp - 1];
                A[temp - 1] = temp;
            }
            else{
                break;
            }
        }
        
        for(int i = 0; i < A.length; i++){
            if(A[i] != i + 1){
                return i + 1;
            }
        }
        return A.length + 1;
    }
    

    }


  • 1

    You should consider this problem more carefully. In your for loop, when A[i] == i + 1, you will break. This is obviously wrong!
    Example:[1, 5, 2]; you will return 2; the right answer is 3.

    Also, when A[i] != i + 1, you only swap once; actually, you will need to swap multiple times (of course, more than that). Try to think it more carefully. Good luck!


  • 0
    M

    I see! Thank you! I fixed my code and it finally passed all the test cases. :)


Log in to reply
 

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