Search This Blog

Monday, December 10, 2012

LeetCode:Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].

public class Solution {
    public int removeDuplicates(int[] A) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(A.length<=1) return A.length;
        int i=1,j=1;
        
        while(j<A.length){
            if(A[j]>A[i-1]){
                 A[i]=A[j];
                 i++;
                 j=i;
            }else{
               j++;
            }
        }
        return i;
    }
}

5 comments:

Unknown said...

Your code is the neatest one I ever seen!!

Xun said...

+Lexie Kwok Good to know!

Xun said...

+Lexie Kwok Good to know!

Anonymous said...

Instead of j = i, it should be j++.

Anonymous said...

didnt work actually