26. Remove Duplicates from Sorted Array

来源:互联网 发布:手机淘宝怎么登陆卖家 编辑:程序博客网 时间:2024/05/21 07:47

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],

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.

给定一个排过序的数组,删除数组中的重复元素,使得每个元素只出现一次,返回删除后的新长度。要求不能分配额外的空间给另外的数组。

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

这个解法可以归结为“两个指针”问题。

【两个指针】因为这个数组已经排过序,所以我们可以用两个指针i和j,i表示跑得慢的,j表示跑得快的。只要nums[i]=nums[j],我们令j自增1来跳过这些重复元素。
当我们遇到nums[j]≠nums[i]时,当前重复元素已经结束所以我们必须拷贝它的值到nums[i+1]中。然后i递增,我们重复这个过程直到j到达数组的结尾。

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;}

Complexity analysis

  • Time complextiy : O(n)O(n). Assume that nn is the length of array. Each of ii and jj traverses at most nn steps.

  • Space complexity : O(1)O(1).