26.RemoveDuplicatesfromSortedArray

来源:互联网 发布:网页抢购软件 编辑:程序博客网 时间:2024/04/30 00:37

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being1 and 2 respectively. It doesn't matter what you leave beyond the new length.


官方时间复杂度为O(n),空间复杂度为O(1)的算法如下:

public int removeDuplicates(int[] nums) {    if (nums.length == 0) return 0;    int i = 0;    for (int j = 1; j < nums.length; j++) {        if (nums[j] != nums[i]) {            i++;            nums[i] = nums[j];        }    }    return i + 1;}