您的位置:首页 > 职场人生

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

2017-11-28 12:08 429 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 刷题 面试 Java