Thursday, June 6, 2013

Remove Duplicates from Sorted Array@leetcode


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].

» Solve this problem

On the first thought, I wanted to start from the end of the array. Set two pointers, to compare the value that two pointers point to. If they equals to each other, then I will move all the elements after one step ahead. But, this is cost tooooo much time and complicated!

I found a really good solution online, which is to check value of elements from the beginning of the array. Compare the value of last elem in array, if equal, then skip, if not, add to the end of the array. 

Because it only need to return the length of the new array, so we can set a counter to count how many elements we have added to the end of the array instead of moving elements. 


1 comment:

  1. maybe the following solution can be better, which avoid extra copy.
    public int removeDuplicates(int[] A) {
    if(A == null) {
    return 0;
    }
    int n = A.length;
    if(n <= 1) {
    return n;
    }
    int i = 0;
    for(int j = 1; j < n; ++j) {
    if(A[j] != A[i]) {
    ++i;
    if(i != j) {
    A[i] = A[j];
    }
    }
    }
    return i+1;
    }

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...