跳至主要內容

26. 删除有序数组中的重复项


26. 删除有序数组中的重复项

🟢   🔖  数组 双指针  🔗 力扣open in new window LeetCodeopen in new window

题目

Given an integer array nums sorted in non-decreasing order , remove the duplicates in-placeopen in new window such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements innums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

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:

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.

题目大意

给定一个有序数组 nums,对数组中的元素进行去重,使得原数组中的每个元素只有一个。最后返回去重以后数组的长度值。

不能使用额外的数组空间,在原地修改数组,并在使用 O(1) 额外空间的条件下完成。

解题思路

这道题和 第 283 题第 27 题 基本一致,283 题是删除 0,27 题是删除指定元素,这一题是删除重复元素,实质是一样的。

因为数组是有序的,那么重复的元素一定会相邻。

删除重复元素,实际上就是将不重复的元素移到数组左侧。考虑使用双指针。具体算法如下:

  1. 定义两个快慢指针 slowfast。其中 slow 指向去除重复元素后的数组的末尾位置。fast 指向当前元素。
  2. slow 在后, fast 在前。
  3. 比较 slow 位置上元素值和 fast 位置上元素值是否相等。
    • 如果不相等,则将 slow 后移一位,将 fast 指向位置的元素复制到 slow 位置上;
    • 如果相等,则不作处理;
  4. fast 右移 1 位。
  5. 重复上述 3 ~ 4 步,直到 fast 等于数组长度。
  6. 返回 slow + 1 即为新数组长度。

复杂度分析

  • 时间复杂度O(n),其中n 表示 nums 的长度,需要遍历数组一遍。
  • 空间复杂度O(1),用了常数个变量存储中间状态。

代码

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
	const len = nums.length;
	if (len == 0) return 0;

	let slow = 0;
	for (let fast = 0; fast < len; fast++) {
		if (nums[slow] != nums[fast]) {
			slow++;
			nums[slow] = nums[fast];
		}
	}
	return slow + 1;
};

相关题目

题号标题题解标签难度力扣
27移除元素[✓]数组 双指针🟢🀄️open in new window 🔗open in new window
80删除有序数组中的重复项 II[✓]数组 双指针🟠🀄️open in new window 🔗open in new window
2460对数组执行操作数组 双指针 模拟🟢🀄️open in new window 🔗open in new window
2615等值距离和数组 哈希表 前缀和🟠🀄️open in new window 🔗open in new window