26.Remove Duplicates from Sorted Array(Easy)

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.
給定一個已排序的數(shù)組,去掉其中重復(fù)的元素,使得每個元素只出現(xiàn)一次,并返回新數(shù)組的長度。
不要為數(shù)組分配額外的空間,你必須在常量內(nèi)存中進行操作

  意思不難理解,就是一個已經(jīng)排好序的數(shù)組然后把不同的數(shù)抽出來組成一個新的數(shù)組,這里說的不要額外分配空間的意思是不要new一個新的數(shù)組,直接在原來傳進來的數(shù)組上進行操作,從第一位開始重新構(gòu)建一個長度為返回值得數(shù)組即可,長度后面有沒有元素都沒有關(guān)系,不用管

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.

My Solution

(Java) Version 1 Time: 15ms:

  因為數(shù)組已經(jīng)排好序了,所以只要從前面向后遍歷,遇到不一樣的數(shù)就放到前面去,自此組成新的數(shù)組

public class Solution {
    public int removeDuplicates(int[] nums) {
        int p=0,length=nums.length;
        for(int i=0;i<length;i++){
            if(nums[i]!=nums[p]){
                p++;
                nums[p]=nums[i];
            }
        }
        return p+1;
    }
}

(Java) Version 2 Time: 13ms (By MadDetective):

  這道題應(yīng)該是沒有什么優(yōu)化的空間了,都是O(n)復(fù)雜度,沒有什么好對比,習(xí)慣性貼一個略有不同的實現(xiàn),時間自然是沒有優(yōu)劣之分

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums==null) return 0;
        int i=0, j=1;
        while(j<nums.length){
            if(nums[i]==nums[j]){
                j++;
            }else {
                i++;
                nums[i] = nums[j]; 
                j++;
            }
        }
        return i+1;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容