从有序数组中移除相等的数值

题目描述

  • 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 A =[1,1,2],
Your function should return length =2, and A is now[1,2].

题目大意

给定一个有序数组,移除其中相等的值,并将移除后的数组长度返回。如例子所示。

思路

最笨的办法就是挨个比较,每次发现了相等的数,就把后边的数都前移一位。
这里用的办法是:维护两个指针,第一个指针记录不相同的数值,第二个指针挨个向后遍历,不相同就用第一个指针记录下来。

代码

int removeDuplicates(int A[], int n) {
    if(A==NULL || n<1)return n;
    int count = 1; // count记录不重复元素的个数
    for(int i=1; i<n; i++)
    {
        if(A[i] != A[i-1]) // 相等就跳过
            A[count++] = A[i]; // 不相等就留下
    }
    return count;
}
  • 以上。

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值