26.Remove Duplicates from Sorted Array

本文介绍了一种不使用额外空间的方法来移除已排序数组中的重复元素,并提供了两种解决方案:一种是通过指针直接修改原数组;另一种是利用set容器特性,尽管这不符合题目的空间复杂度要求。

题目:
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn’t matter what values are set beyond the returned length.
解析:移除已排序数组中的重复元素。
方法一:使用指针的方式直接对原数组进行修改。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i=0,j=0;
        int n=nums.size();
        if(n==0) return 0;
        while(j<n)
        {
         if(nums[i]==nums[j]) j++;
         else
            nums[++i]=nums[j++];
        }
         return i+1;
    }
};

特别注意,如果没有第三条语句,会导致运行超时。一般对这种特殊情况都需要单独处理。
方法二:使用set容器特性-set集合中没有重复的元素,但是不符合题目要求(虽然accetped)有额外的空间资源

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0) return 0;
        set<int> st(nums.begin(),nums.end());
        nums.assign(st.begin(),st.end());
        return nums.size();
    }
};

set是关联式容器,它里面的元素都是排好序的,并且set集合中没有重复的元素。assign将区间[first,last)中的元素赋值到当前的vector容器中。第二种方法的时间复杂度比第一种方法要大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值