「这是我参与11月更文挑战的第22天,活动详情查看:2021最后一次更文挑战」
26. Remove Duplicates from Sorted Array
题目
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
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 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
0 <= nums.length <= 3 * 10^4
-100 <= nums[i] <= 100
nums
is sorted in non-decreasing order.
题目大意
不借助额外空间,给有序数组去重,将去重后的所有元素放在数组开头,返回去重后的剩余元素个数
解释:因为传入nums
是一个引用,对其原地操作后,OJ 可以根据返回的元素个数通过nums
得到“新数组”,从而判断去重是否正确
解题思路
双指针:设定两个指针slow
、fast
- 初始:
slow = 0
、fast = 1
- 比较
nums[slow]
和nums[fast]
是否相等,若相等fast++
(即快指针指向下一个元素) - 重复第
2
步直到fast
找到不同于slow
指向的元素 nums[++slow] = nums[fast++]
,即将fast
指向的元素放到slow
后面,并且两个指针都向后移动一位- 重复
2~3
步直到fast === nums.length
- 返回
slow + 1
,因为slow
指向“新数组”最后一个元素
代码
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function (nums) {
if (nums.length === 0) {
return 0;
}
let slow = 0;
for (let fast = 1; fast < nums.length; fast++) {
if (nums[slow] !== nums[fast]) {
nums[++slow] = nums[fast];
}
}
return slow + 1;
};
复杂度
时间:O(n)
,最坏情况fast
、slow
遍历完数组
空间:O(1)