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

题目大意为:不开辟额外的空间,将一个已经排序过的数组中的重复数字去除掉。


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


/*
思路:这个不开辟额外的空间。
将数组中含有1次以上的数字全部去除掉 
*/
int removeDuplicates(int* nums, int numsSize) {
    if(nums==NULL||numsSize<1){
        return 0;
    }
    if(numsSize==1){
        return numsSize;
    }
    int index1=0;
    int index2=1;
    int count=1;
    for(int i=1;i<numsSize;i++){

        if(nums[index1]==nums[i])
            continue;
        //不相等就要进行拷贝
        if(i-index2!=0){//中间有Duplicate需要覆盖 
            nums[index2]=nums[i];
            index1=i;
            index2++;                                       
        }
        else{//不需要拷贝,但是需要更新,其实这里的代码可以与上面的代码提取出来并合并,但是这样写逻辑更容易理解一点。
            index1=i;
            index2++; 
        }

    }
//  for(int i=0;i<index2;i++){
//      printf("%d   ",nums[i]);
//  } 
    return index2; 

}

int main(void){
    int k;
    while(scanf("%d",&k)!=EOF&&k>0){
        int *arr=(int *)malloc(k*sizeof(int));
        if(arr==NULL){
            exit(EXIT_FAILURE);
        }
        for(int i=0;i<k;i++){
            scanf("%d",arr+i);
        }
        int len=removeDuplicates(arr,k);
        //printf("%d\n",len);

    }
}

此题比较简单,AC结果如下

从结果可以看出,上面这种方法的效率并不高,因此需要寻找更高效的方法。

出于好奇,将如下代码的公共代码进行了提取

    if(i-index2!=0){//中间有Duplicate需要覆盖 
            nums[index2]=nums[i];
            index1=i;
            index2++;                                       
        }
        else{//不需要拷贝,但是需要更新,其实这里的代码可以与上面的代码提取出来并合并,但是这样写逻辑更容易理解一点。
            index1=i;
            index2++; 
        }

代码如下

        if(i-index2!=0){//中间有Duplicate需要覆盖 
            nums[index2]=nums[i];
        }
        index1=i;
        index2++; 

结果吓我一跳,时间居然少了很多(大概4ms),分析了下原因,虽然在执行代码上面并没有多大的改变,原因可能在于在编译阶段花了一定的时间。AC结果如下

网上的代码

看了下网上的代码,发现自己是多么的渣,别人的代码是多么的简单,代码如下:


int removeDuplicates(int* nums, int numsSize) {
    if(nums==NULL||numsSize<1){
        return 0;
    }
    int index=1;//用于指向即将要覆盖的位置。 
    for(int i=1;i<numsSize;i++){
        if(nums[i]!=nums[i-1]){
            nums[index]=nums[i];
            index++;
        }
    }
    return index; 

}

上面的代码在时间上没有改进,Runtime: 12 ms

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值