My java solution is about 264 ms fast. How should I optimize to boost it a little bit faster?


  • 0
    N
    public class Solution {
    public int removeDuplicates(int[] A) {
        int newLength = A.length;
        int newLoc = 0;
        int oldLoc = 0;
        int count = 1;
        
        if (newLength <= 2)
            return newLength;
            
        int curVal = A[oldLoc];
    
        
        while (newLoc < (newLength - 1)) {
            oldLoc++;
        
            if (A[oldLoc] == curVal) {
                if (count >= 2) {
                    newLength--;
                }
                else {
                    count++;
                    A[++newLoc] = A[oldLoc];
                }
            }
            else {
                A[++newLoc] = A[oldLoc];
                curVal = A[oldLoc];
                count = 1;
            }
        }
        
        return newLength;
        
    }
    

    }


Log in to reply
 

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