Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

https://leetcode.com/problems/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],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

算法思想:

1)定义两个index:i和j。i指向的是新的array的最后一个元素,j依次遍历整个数组。i初始化为0,j初始化为1
2)如果i指向的元素和j指向的元素相等,那么不做任何操作;如果i指向的元素和j指向的元素不相等,那么i就指向i的后面一个元素,并且i指向的元素的值改为j指向的元素的值。判断完之后j向前移动一步(j需要依次遍历整个数组)
3)j遍历完了之后,程序终止。[0, i]就是新的数组。

代码清单如下:

public class Solution {
    public int removeDuplicates(int[] nums) {
        int length = nums.length;
        if (length <= 1) {
            return length;
        }
        
        int i = 0;
        for (int j = 1; j < length; j++) {
            if (nums[i] != nums[j]) {
                i = i + 1;
                nums[i] = nums[j];
            }
        }
        return i+1;
    }
}
posted @ 2015-08-18 17:48  TinaYo  阅读(141)  评论(0编辑  收藏  举报