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

删除重复的数,并返回数组的长度


题目解析:

这道题目可以从快速排序算法得到启发:快排有两种,一种从左向右遍历,碰到比key大的,就将放到后面,再从后向前遍历;另一种是设两个下标指针,i和j,i指向当前遍历的数据里面都比key小的数据,i->j-1之间都是大于key的数据,j指向当前要判断的数据,如果arr[j]<=key,就将arr[i+1]和arr[j]交换。

但这个题目当中只是让删除数据,我们可以利用上述第二种方法,但不交换,直接arr[i+1] = arr[j]。不过具体实现的时候,和快排有一点点差别。

#include <stdio.h>
#include <stdlib.h>

int RemoveDuplicates(int arr[],int len);

int main()
{
    int arr[10];
    int n;

    while(scanf("%d",&n) != EOF){
        for(int i = 0;i < n;++i)
            scanf("%d",&arr[i]);
        int len = RemoveDuplicates(arr,n);
        printf("len = %d\n",len);
        for(int i = 0;i < len;++i)
            printf("%d ",arr[i]);
        printf("\n");
    }

    return 0;
}


int RemoveDuplicates(int arr[],int len)
{
    int i,j;

    if(arr == NULL || len <= 0)
        return 0;
    i = 0;
    j = 1;
    while(j < len){
        if(arr[i] != arr[j] && ++i != j)
            arr[i] = arr[j];
        ++j;
    }
    return i+1;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值