Leetcode c语言-Remove Duplicates from Sorted Array

来源:互联网 发布:新代数控车床编程实例 编辑:程序博客网 时间:2024/06/08 17:49

Title:

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.


这道题目很简单,但如果只按照题目意思会更简单,题目意思是只需要返回长度,而不用管其他任何事。

但如果你天真的只返回长度,而不修改数组。那么你会发现你胸有成竹的几行代码,会报错,原因就是你没有对应的修改数组。也就是说也要把数组中重复的元素删掉。但题目要求没有提到这个,让人有点无语。也终于明白为什么这道题的踩那么多了:




因此,我们需要修改数组,而且不能创建新的数组,只能在固定空间修改。

很好办,遍历每一个元素,然后如果这个元素与它的下一个元素不同,说明它是唯一的,这个时候保存即可。如果相同,就不做任何操作,继续遍历下一个元素。


solution:

int removeDuplicates(int* nums, int numsSize) {    int len=0;    int res;    int i;        if (numsSize==0)        return 0;    if (numsSize==1)        return 1;        for (i=0;i<numsSize;i++) {        if (nums[i]!=nums[i+1]) {            nums[len]=nums[i];            len++;                  }         else if(i==numsSize-1 && nums[i]==nums[i+1]) {            nums[len]=nums[i];            len++;                  }               }    return len;} 


要注意的一种情况,就是最后1个元素如果是0的话,i+1表示数组的结束符,也是0,这个时候要做特殊处理,保证0存入。

else if(i==numsSize-1 && nums[i]==nums[i+1]) {            nums[len]=nums[i];            len++;     


阅读全文
0 0
原创粉丝点击