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

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

题目描述

  • 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
欢迎来踩~~~~


猜你喜欢

转载自blog.csdn.net/w7239/article/details/85109811