LeetCode Remove Duplicates from Sorted Array

本文介绍了如何在常量内存下删除有序数组中的重复元素,包括两种实现方式:一种是通过迭代器操作直接修改原数组,另一种利用STL库中的unique函数进行去重。

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

Remove Duplicates from Sorted Array Total Accepted: 52196 Total Submissions: 165553 My Submissions Question Solution
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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

题意:删除有序数组的重复元素

代码一:

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n==0)return 0;
        int index=0;
        for(int i=1;i<n;++i)
        {
            if(A[i]!=A[i-1])
                A[++index]=A[i];
        }
        return index+1;
    }
};

161 / 161 test cases passed.
Status: Accepted
Runtime: 37 ms

代码二(网络获取):

// LeetCode, Remove Duplicates from Sorted Array
// 使用STL,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
    return distance(A, unique(A, A + n));
    }
}

161 / 161 test cases passed.
Status: Accepted
Runtime: 34 ms
在STL中unique函数是一个去重函数, unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。
distance返回两个迭代器之间的距离。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值