LeetCode-26. Remove Duplicates from Sorted Array

364 阅读2分钟

「这是我参与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得到“新数组”,从而判断去重是否正确

解题思路

双指针:设定两个指针slowfast

  1. 初始:slow = 0fast = 1
  2. 比较nums[slow]nums[fast]是否相等,若相等fast++(即快指针指向下一个元素)
  3. 重复第2步直到fast找到不同于slow指向的元素
  4. nums[++slow] = nums[fast++],即将fast指向的元素放到slow后面,并且两个指针都向后移动一位
  5. 重复2~3步直到fast === nums.length
  6. 返回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),最坏情况fastslow遍历完数组

空间:O(1)