4---LeetCode【tag: Array】【Remove Duplicates from Sorted Array】|C语言|总结

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.

问题分析:

给一个int型数组,去掉数组中重复的数据,return新的数组长度。注意不要分配额外的空间给其他的数组,必须在不变长度的存储中进行操作。

constant memory是指不变大小的内存吗?

不使用another array,直接在输入的num中去掉重复的数据吗?怎么去?

可能的思路:

1. 声明一个变量rpt_num = 0;

2. 循环比较数组中的数据,找到一个重复的数据就rpt_num + 1;

3. return numsSize - rpt_num

int removeDuplicates(int* nums, int numsSize) {
    
    int rpt_num = 0;
    for(int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] == nums[j]) {
                rpt_num += 1;
                break;
            }
        }
    }
    return (numsSize - rpt_num);
}

测试不通过,还需要返回数组

所以题目的意思是:将不重复的数据放在数组的前面,即从下标0开始排列,然后return新的数组长度???

新的思路:

1. 还是循环,从下标1开始  ---- i = 1 到 numsSize - 1;

2. 内循环不同,这次从前面开始找 ---- j = 0 到 i - 1;

3. 声明一个int index做下标寄存,若当前数据nums[i] 与前面的某个数据相同,则index = index,若不同则nums[index] = nums[i],index = index + 1;

4. 返回index。

int removeDuplicates(int* nums, int numsSize) {
    
    int index = 1;
    int tmp;
    for(int i = 1; i < numsSize; i++) {
        tmp = 1;
        for (int j = 0; j < i; j++) {
            if (nums[i] == nums[j]) {
                tmp = 0;
                break;
            }
        }
        nums[index] = nums[i];
        index += tmp;
    }
    return index;
}


测试不通过,161个case通过了160个,[ ]没有考虑到

在代码开始的地方加上 if (numsSize == 0) return 0;

这样倒是通过了,但是效率低的可怕,只打败了1.46%的代码,虽然早就知道这样效率低,但是没想到这么低

思来想去,还是去拿点别人的代码吧

----

题目理解错了,原来sorted array是已经排序过的数组,我以为是分类数组,所以我虽然理解错了,但是代码也能通过,因为[1, 1, 2, 1]不属于test case


知识点:

1. sorted array -- 排序数组

2. 测试时要考虑各种情况,边界和NULL




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值