Remove Duplicates from Sorted Array

Remove duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appears only once and return the new length.

Note that even though we want you to return the new length, make sure to change the original array as well in place

Do not allocate extra space for another array, you must do this in place with constant memory.

Example:
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
 
Method:

We keep a size of current no-duplicate range, starting from index 1, we check if current number equals to the last number in the no-duplicate range, if yes, we keep going, otherwise we set the index of size to be current number, and increase size.

Solution:

Time: O(n)
Space: O(1)

public class Solution {
    public int removeDuplicates(ArrayList<Integer> a) {
        if (a.size() <= 1) return a.size();
        int size = 1;
        for (int i = 1; i < a.size(); i ++) {
            int curr = a.get(i);
            int prev = a.get(size - 1);
            if (curr != prev) {
                a.set(size, curr);
                size ++;
            }
        }
        while (a.size() > size) {
            a.remove(a.size() - 1);
        }
        return size;
    }
}