leetcode-Remove Duplicates from Sorted Array
question:Remove Duplicates from Sorted Array
Given a sorted array nums, 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.
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
Example 1:
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 returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length =5
, with the first five elements ofnums
being modified to0
,1
,2
,3
, and4
respectively. It doesn't matter what values are set beyond the returned length.
Link:https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/
思路:
理解1:定义两个索引,一个头索引,一个尾索引,头索引指向找到的数(也是刚被移动的数),尾索引找不相同的数;比如 [1,1,2],
经过循环后;end=2,head=1;
理解2:一个快指针,一个慢指针,慢指针的下标是快指针找到不相同的元素移动到数组的那个位置的下标;(同样也是不重复元素的个数)
class Solution { public int removeDuplicates(int[] nums) { int head=0 ,end=0; /** 定义一个头索引和一个尾索引,头索引指向刚被移动的数.尾索引找不相同的数, 并且移动到头索引的下下一个 */ for (int i = 0; i < nums.length; i++) { if(nums[head]!=nums[end]){ nums[head+1]=nums[end]; head++; } end++; } return head+1; } }
作者:8亩田
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接.
本文如对您有帮助,还请多帮 【推荐】 下此文。
如果喜欢我的文章,请关注我的公众号
如果有疑问,请下面留言