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.

Subscribe to see which companies asked this question.

先翻译题目:移除给定有序数组中的重复元素,然后返回数组长度;不可额外创建数组,只允许使用当前数组空间;

我的思路是设置两个游标,i=0,j=1;因为这是一个有序数组,所以必定后面的元素大于或者等于前面的元素;

然后从j=1与i=0相比较,如果相等则j++,又与i=0相比较,直到不等为止,然后i++,将此时的j对应的元素赋值给i;

由于最后i指向的是最后一个元素的位置,所以数组长度还需要加一,i++,返回;

这里做的时候一开始没考虑如果是个空数组怎样,所以后来加上了对空数组的判断;

以下为代码示例:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值