easy: 100 · Remove Duplicates from Sorted Array - LintCode

# Description

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.

Example 1:

Input:

nums = []

Output:

0

Explanation:
The array is empty.

Example 2:

Input:

nums = [1,1,2]

Output:

2

# Solution

int left = 0;
int right = 1;
看right是否和left相同,當不同的時候 讓left + 1, 且等於right
e.g,  l = 0, r = 1
    [ 1, 1, 2 ] 
       ^  ^  
       l  r
   第一個1 和 第二個 1 一樣,然後 r繼續loop, r++;
第二次 : l = 0, r = 2
	 [ 1, 1, 2 ] 
       ^     ^
       l     r
   l 和 r 的值不一樣,於是l+1, 讓它等於 "2";
最後返回left +1, +1是因為反回的是字符串的長度。

public class Solution {
    /*
     * @param nums: An ineger array
     * @return: An integer
     */
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        int j = 0;
        for (int i = 1; i < nums.length; i++){
            if (nums[i] != nums[i - 1]){
                j++;
                nums[j] = nums[i];
            }
        }
        return j + 1;
    }
}