【LeetCode26】【Remove Duplicates from Sorted Array】

来源:互联网 发布:濮院淘宝供货 编辑:程序博客网 时间:2024/06/04 17:41

题目:

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