LeetCode——remove-duplicates-from-sorted-array(从排序数组中删除重复项)

1.题目描述

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].

题意大概就是:要求不能另外开辟数组保存值,只能在已有的内存空间排序进行操作。

2.结题思路

(1)特殊情况:数组为空或者给定的长度为负数的时候,返回0;
(2)定义两个变量i,j做索引值,j指向数组中下标为0的位置,i指向数组中下标为1的位置:当A[j]!=A[i]的时候,i和j同时向后走,否则i向后走;进行循环。
如下图:
这里写图片描述

3.实现代码
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n<=0)return 0;
        int k=0;
        for(int i=1;i<n;i++)
        {
            if(A[k]!=A[i])
            {
                A[++k]=A[i];
            }
        }
        return k+1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值