Monday, June 9, 2014

Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Solution1: two pointers 不考虑顺序
两个指针left和right,left指第一个element,right指最后一个element。
如果A[right] == elem,直接跳过。
然后如果A[left] == elem,将right所指的element复制给left,left++, right--。
Run time complexity is O(n), constant space.
public class Solution {
    public int removeElement(int[] A, int elem) {
        if(A == null || A.length == 0)
            return 0;
        
        int l = 0, r = A.length - 1;
        while(l <= r) {
            if(A[r] == elem) {
                r--;
                continue;
            }
            
            if(A[l] == elem) {
                A[l] = A[r];
                l++;
                r--;
            }else {
                l++;
            }
        }
        
        return r + 1;
    }
}
Solution2:仍然保持顺序
public class Solution {
    public int removeElement(int[] A, int elem) {
        if(A == null || A.length == 0)
            return 0;
        
        int p1 = 0, p2 = 0;
        while(p2 < A.length) {
            if(A[p2] == elem) {
                p2++;
            }else {
                A[p1] = A[p2];
                p1++;
                p2++;
            }
        }
        
        return p1;
    }
}

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

Solution:
Run time complexity is O(n), constant space.
public class Solution {
    public int removeDuplicates(int[] A) {
        if(A == null || A.length == 0) {
            return 0;
        }
        
        int p1 = 0, p2 = 0;
        while(p2 < A.length) {
            if(A[p1] == A[p2]) {
                p2++;
            }else {
                p1++;
                A[p1] = A[p2];
                p2++;
            }
        }
        
        return p1 + 1;
    }
}