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

来源:互联网 发布:作为打印机网络主机 编辑:程序博客网 时间:2024/06/14 02:52

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
原创粉丝点击