LeetCode 26. Remove Duplicates from Sorted Array

本文介绍了一种在原地且使用常数级额外空间的情况下,去除已排序数组中重复元素的方法。通过迭代器遍历数组,利用erase方法删除重复项,并返回新的数组长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

问题描述:
题目的要求是给定一个有序的数组,将数组里重复的元素去掉,函数的返回结果是去掉重复元素后的数组长度。
原本以为只要返回去掉重复元素后的数组长度,但是后来发现了同时要将重复的元素从原数组里去掉,因为可以看到题目给出的函数中数组是作为引用输入,所以函数返回之后数组也已经变成去重之后的数组。

解题思路:
因为题目给出的数组是已经排好序了,所以我们可以设定一个current表示上一个元素,当遍历到第i个元素nums[i]

  • 如果nums[i]与current相同,表明nums[i]是重复的元素,将nums[i]从数组中去掉,继续访问下一个元素,current的值不变;
  • 如果nums[i]与current不相同,表明已经没有与current相同的元素了,可以将nums[i]的值赋给current,继续访问下一个元素。

这里有一个需要注意的问题是如何从vector中去除某个元素,因为我用的iterator遍历vector,所以可以用erase来去除某个元素,这个函数的参数是需要去除的元素的iterator,返回被去除元素的下一个元素的iterator。

代码:

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        vector<int>::iterator it = nums.begin();
        int current = *it;
        it++;
        while (it != nums.end()) {
            if (current == *it) {
                it = nums.erase(it);
                continue;
            }
            else {
                current = *it;
            }
            if(it == nums.end()) break;
            it++;
        }
        return nums.size();
    }
};

int main(int argc, const char * argv[]) {
    int array[] = {1, 1, 1};
    int count = sizeof(array) / sizeof(int);
    vector<int> nums(array, array + count);
    Solution sln;
    cout << sln.removeDuplicates(nums) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值