Leetcode c语言-Remove Duplicates from Sorted Array

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++;     


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值