26. 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 nums = [1,1,2],

思路: 两指针方法。一个指针i遍历数组, 另一个指针newIndex只取不重复的数. 初始newIndex=0, 指针i从1到nums.length遍历. 判断条件if(nums[newIndex] != nums[i]){newIndex++; nums[newIndex]=nums[i]}构建新的数组. 最后新数组长度返回newIndex + 1。

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return 1;
        int newIndex = 0;
        int i = 1;
        while(i < nums.length) {
            if (nums[i] != nums[newIndex]) {
                newIndex++;
                nums[newIndex] = nums[i];
            }
            i++;
        }
        return newIndex + 1;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s