【LeetCode 面试经典150题】26. Remove Duplicates from Sorted Array 在有序数组中移除重复元素

2024-01-03 05:58:32

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. Then return the number of unique elements in nums.

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.

中文释义

给定一个按非递减顺序排序的整数数组 nums,就地删除重复项,使每个唯一元素只出现一次。元素的相对顺序应保持不变。然后返回 nums 中唯一元素的数量。

考虑 nums 中唯一元素的数量为 k。为了通过验证,你需要做以下事情:

  • 修改数组 nums,使得 nums 的前 k 个元素包含最初在 nums 中出现的唯一元素。nums 的剩余元素不重要,nums 的大小也不重要。
  • 返回 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).

约束条件:

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

解题思路

方法

双指针方法。

步骤

  1. 初始化两个指针:

    • index(慢指针):用于在数组中构建不重复的新数组。
    • i(快指针):用于遍历原数组。
  2. 遍历数组:

    • 遍历数组时,使用快指针 i 来检查每个元素。
    • 如果当前元素 nums[i] 不等于前一个元素nums[i - 1],则将其复制到慢指针 index 的当前位置,并递增 index。
  3. 更新数组长度:

    • 遍历完成后,index + 1 就是新数组的长度,即不包含值 val 的元素数量。
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        // 非降序数组,原地移除重复出现的元素,保证每个元素只出现一次。
        // 即 原地移除与前面位置相等的元素
        int index = -1;
        for (int i = 0; i < nums.size(); i++) {
            if (i == 0 || nums[i - 1] != nums[i]) {
                nums[++index] = nums[i];
            }
        }
        return index + 1;
    }
};

文章来源:https://blog.csdn.net/qq_43513394/article/details/135352541
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。