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

文章介绍了如何在给定的非递减整数数组中,就地删除重复元素,保持相对顺序,返回唯一元素数量。通过双指针方法,使用快慢指针遍历数组并更新新数组。
摘要由CSDN通过智能技术生成

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;
    }
};
  • 19
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值