美文网首页
LeetCode_Problem_27_Remove_Eleme

LeetCode_Problem_27_Remove_Eleme

作者: 吃柠檬的鸮 | 来源:发表于2019-03-07 22:04 被阅读0次

    Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

    Example 1:
    Given 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 returned length.

    Example 2:
    Given nums = [0,0,1,1,1,2,2,3,3,4],
    Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
    It doesn't matter what values are set beyond the returned length.

    题目要求在不申请额外数组空间的情况下删除数组中的重复元素,即空间复杂度为 O(1),个人思路是:

    1. 设置一前一后两个下标索引 idxii 用来遍历数组,idx 用来标识当前需要判断是否重复的数字的值(idx 始终小于 i,因为和自身比较没有意义);
    2. 初始化 idx 为 0,i 为 1;
    3. 判断传入数组长度 size,若 size 小于 2,返回 size,程序结束;否则执行下一步;
    4. 比较 num[idx]num[i],如果不相等,则 ++idx 移动到下一个新的位置保存新值;
    5. ++i 进行下一个元素检验,如果 i < size,执行步骤 4;否则,返回 idx + 1,程序结束。
    int removeDuplicates(int* nums, int numsSize) {
        int i;
        int idx;
        
        if (numsSize < 2) {
            return numsSize;
        }
        
        for (i = 1, idx = 0; i != numsSize; ++i) {
            if (nums[idx] != nums[i]) {
                nums[++idx] = nums[i];
            }
        }
        
        // idx 是下标索引,最终返回的是实际数组的长度
        return (idx + 1);
    }
    

    相关文章

      网友评论

          本文标题:LeetCode_Problem_27_Remove_Eleme

          本文链接:https://www.haomeiwen.com/subject/wlchpqtx.html