Why one code is accepted but another very similar has runtime error


  • 0
    J

    Hi all,

    I submitted this code, and it has runtime error:

    public class Solution {
        public int removeDuplicates(int[] A) {
            int uniqueCount = 0;
            int len = A.length;
    
            for(int i = 0; i < len; i++) {
                if (uniqueCount == 0 || A[i] != A[i-1]) { //encounter a new element
                    A[uniqueCount++] = A[i];
                }
            }
    
            return uniqueCount;
        }
    }
    

    After I change a little bit to:

    public class Solution {
        public int removeDuplicates(int[] A) {
            int uniqueCount = 1;
            int len = A.length;
    
            for(int i = 1; i < len; i++) {
                if (A[i] != A[i-1]) { //encounter a new element
                    A[uniqueCount++] = A[i];
                }
            }
    
            return uniqueCount;
        }
    }
    

    it is accepted, and takes 420ms.

    I am wondering why it is the case, as I think the first code should be a little faster as it has one less comparison, right?

    Xiang


  • 0
    M

    Do you happen to have the input you got the error on?


  • 1
    G
    1. The first solution works, not the second one
    2. The second fails because it throws errors for an empty array: your uniqueCount is at least 1 in this case.
    3. To fix the second solution, just handle the edge case separately.

Log in to reply
 

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