LeetCode-Easy刷题(7) Remove Duplicates from Sorted Array

来源:互联网 发布:恒扬数据副总经理 编辑:程序博客网 时间:2024/05/20 07:50

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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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.

给定一个排好序的数组后,删除重复的副本,这样每个元素只出现一次,并返回新的长度。 不要为另一个数组分配额外的空间,您必须通过修改带有O(1)额外内存的输入数组来实现这一点。

public static int removeDuplicates(int[] nums) {        if(nums ==null || nums.length <1){            return 0;        }        int index = 1;//从第二个元素开始才会出现重复        for (int i = 1; i < nums.length; i++) {            if(nums[i]!=nums[i-1]){                nums[index] = nums[i];                index++;            }        }        return index;    }


阅读全文
0 0
原创粉丝点击