26. 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.

對(duì)于排序數(shù)組,相同的值一定是聚集在一起的。
我一開(kāi)始的想法是交換尾部和頭部而不是覆蓋,交換算法是不穩(wěn)定的,這意味著我破壞了原來(lái)的有序性,從而判斷一個(gè)部分是否含有一個(gè)VAL從常數(shù)時(shí)間(只要判斷部分的末尾是否等于VAL)成了線性。這是一種不佳的退化。
這和remove element是不同的 前者的判斷式子是O(1)(是否等于一個(gè)特定的值),而在這里,要判斷是否重復(fù)在交換的情況下變成了O(N).(因?yàn)榻粨Q破壞了排序性)。

下面這張寫法是和Remove Element 差不多的 說(shuō)實(shí)話 我也不知道自己為啥要這樣寫。這張完全沒(méi)有利用有序的信息,采用的是暴力搜索,O(N2),可能我當(dāng)時(shí)腦子進(jìn)水了。

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

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

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