题目描述
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
要求
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
示例
一
1 | 给定数组 nums = [1,1,2], |
二
1 | 给定 nums = [0,0,1,1,1,2,2,3,3,4], |
实现
1 | public int removeDuplicates(int[] nums) { |
总结
数组首先是排好序的
使用两个指针i
和count
, 其中count
是慢指针,i
为快指针
当nums[i-1] = nums[i]
, 我们就增加i
跳过重复项
当nums[i-1] != nums[i]
, 此时遇到不同项,就让count++
, 并把当前nums[i]
的值赋给nums[count]
, 重复以上过程,直到到达nums.length
就让所有不重复的值提到了前面。
复杂度分析
时间复杂度:
O(n)
, 假设数组的长度为n
, 那么i
和j
分别最多遍历n
步空间复杂度:
O(1)