【LeetCode】26. Remove Duplicates from Sorted Array

来源:互联网 发布:知乎 不氪金的手游 编辑:程序博客网 时间:2024/05/17 06:06

题目描述:

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 arraynums =[1,1,2],

Your function should return length =2, with the first two elements ofnums being1 and2 respectively. It doesn't matter what you leave beyond the new length.


给定一个排好序的数组,删除重复的元素,这样每个元素只出现一次,并返回新的长度。
不要为另一个数组分配额外的空间,您必须在内存不变的情况下这样做。
例如:给定输入数组nums=[1,1,2],您的函数应该返回长度=2,而nums的前两个元素分别是1和2。你在新的长度之外留下什么并不重要。


这是第一次做的时候的解法:

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

我的最初的想法是数组中的第一个与后面的每一个比较,如果相等,就把后面的依次往前移动,所以有了上面的解法,时间复杂度是O(n²)。后来看了参考答案,时间复杂度是O(n),参考答案相当于用了两个指针,i和j,i从0开始,i所指过的地方都是不与前面重复的,j的作用就是用来找那个不重复的数,找到以后赋值给i所指的地方。用两个指针这样的解法确实没有想到,也很少在做题中用到,不过这次学到了。

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













原创粉丝点击