【LeetCode26】【Remove Duplicates from Sorted Array】

题目:

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.

大意翻译:

给你一个排好序的数组,将数组里的所有不同的数字(设个数为count)移到数组前count位,并返回count。
注意,不可以分配新的数组空间,只能在一个数组里进行操作。

解答代码:

1.我的最初思路java实现:

/**
     * 用时特别久72ms,排名几近倒数,代码复杂难懂。
     * 原因分析:
     * 1.出发点:我从数组中后一个与前一个相同的情况出发,这样需要考虑某一个数之后有几个数字与这个数相同的情况。
     * 2.循环冗余:如果下个数与上个数相同,就将下个数之后的数均前进一格,其实没必要均前进一格,我这样做导致算法时间复杂度急剧上升。
     */

    public int removeDuplicates1(int[] nums) {
            if(nums.length==0){return 0;}
            int count = 0;
            for(int i = 1;i<nums.length-count;i++){
                while(nums[i-1]==nums[i]){
                    for(int k = i+1;k<nums.length-count;k++){
                        nums[k-1] = nums[k];
                    }
                    count++;
                    if(i==nums.length-count){break;}
                }
            }
            return nums.length-count;
    }

2.参考大神后的实现:

/**
     * 从下一个数与上一个数不相同的情况考虑。
     * 循环数组,如果本次循环的数比数组中count位的数大,那么就把count+1位变成本次循环的数,并且将count+1;
     * @return
     */
    public int removeDuplicates2(int[] nums) {
            int count = 0;
            for(int num:nums){
                if(num>nums[count]){
                    nums[++count]=num;
                }
            }
            return count+1;
    }

设计知识点:

题目主要涉及了最基本的[i++][++i]的区别:

“nums[i++] = n” 是先将nums[i] = n,然后i = i+1;
“nums[++i] = n”是先将i=i+1,然后nums[i] = n;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值