LeetCode_Easy心得:26. Remove Duplicates from Sorted Array(C语言)

Given a sorted array, remove the duplicates in place such that each element appear onlyonce and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

/** 题目分析:要求输入一组有序数组,将数组中重复部分删除,也就是说每个数组元素只能出现一次,最后返回该数组的数组长度。同时,不能创建新的数组变量,必须要在输入的数组中操作。 */

Example:

Given input array nums = [1,1,2];

return length=2;

/** 代码思路:①因为要求不可以创建新数组变量,所以就创建两个int表示数组下标,用来操作输入数组内部元素,下标分别是 length=0和 i=0;②从下标0开始比较数组内数字;③当出现重复数时, i下标向后移动一位,直至与 length下标数字数字不重复;④此时,将 i位置数字赋到 length位置处, length下标向后移动一位;⑤重复步骤③,直至数组最后一个数字比完;⑥最后需要返回的是不重复数组的长度,因为当前length表示的数组下标,而长度则需要将下标+1, 因此函数返回值是 length+1。 */

Example:

nums[i] = {1, 1, 2, 3, 3, 3, 4, 5};

nums[length] = {1, 2, 3, 4, 5};        //因为length只能取到4,下标5后面的数组间接滤除了;

//此时,完整的nums[] = {1, 2, 3, 4, 5, 3, 4, 5}; 最后返回的 length = 4+1;


int removeDuplicates(int nums[], int numsSize) {
    int i, length=0;       //下标 i和 length;
    if(numsSize <= 1)   //如果数组长度小于等于1,直接返回;
        return numsSize;
    for(i=1; i<numsSize; i++){
        if(nums[length] != nums[i]){
            length ++;                     //len先自增,因为数组长度已经大于1了;
            nums[length] = nums[i];        //将 i位置数赋给length位置;
        }
    }
    return length + 1;                     //最后因为是返回长度,所以 +1;
}


//LeetCode运行时间:14ms ± 2ms;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值