Remove Duplicates from Sorted Array

来源:互联网 发布:blueray播放器 mac 编辑:程序博客网 时间:2024/05/17 05:54

1.题目

给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度。不要使用额外的数组空间,必须在原地没有额外空间的条件下完成

给出数组A =[1,1,2],你的函数应该返回长度2,此时A=[1,2]

2.算法

这个题目也比较简单,就是维护一个指针,从前向后扫描,如果当前指针指向的数和扫描数不同,则加到数组中

    public int removeDuplicates(int[] nums) {        // write your code here        if (nums.length == 0) {            return 0;        }        int index = 0;        for (int i = 1; i < nums.length; i++) {            if (nums[index] != nums[i]) {                nums[++index] = nums[i];            }        }        return index + 1;    }


    def removeDuplicates(self, A):        # write your code here        if len(A) == 0:            return 0        index = 0        for i in range(1, len(A)):            if A[index] != A[i]:                index += 1                A[index] = A[i]        return index + 1

0 0
原创粉丝点击