LeetCode 26. Remove Duplicates from Sorted Array & LeetCode 27. Remove Element

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

大致意思就是給定一個(gè)已排好序的數(shù)組,刪除數(shù)組中的重復(fù)元素并返回刪除后的數(shù)組大小,刪除操作必須在原數(shù)組中進(jìn)行,不允許我們另建一個(gè)數(shù)組。
因?yàn)榉祷刂抵挥行聰?shù)組的大小,開(kāi)始我以為只要統(tǒng)計(jì)出數(shù)組中的不重復(fù)元素個(gè)數(shù)并返回即可AC,有點(diǎn)native了。本題要求我們?cè)凡僮?,這樣即可驗(yàn)證我們是否刪除了數(shù)組中的重復(fù)元素并得到正確的新數(shù)組,所以光統(tǒng)計(jì)不重復(fù)元素個(gè)數(shù)是不行的。
這里設(shè)置兩個(gè)指針i和j,i指向新數(shù)組的最后一個(gè)元素,j用來(lái)遍歷原數(shù)組,當(dāng)nums[j] == num[i],直接遞增j來(lái)跳過(guò)重復(fù)元素;當(dāng)nums[j] != num[i],先遞增i更新新數(shù)組的尾指針,把nums[j]賦值到新數(shù)組的尾部,再遞增j訪問(wèn)下一個(gè)元素即可。這樣僅需遍歷數(shù)組一遍即可得出新數(shù)組及其大小。
上述算法的時(shí)間復(fù)雜度為O(n),空間復(fù)雜度為O(1)
代碼如下:

public class Solution {
    public int removeDuplicates(int[] nums) {
        
        if (nums.length == 0) 
            return 0;
        int i = 0;  // 新數(shù)組最后一個(gè)元素的指針
        for (int j = 1; j < nums.length; j++) 
        {
            if (nums[j] != nums[i])
                nums[++i] = nums[j];
        }
        return i + 1;
    }
}

LeetCode 27. Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:

Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.

大致意思就是給定一個(gè)數(shù)組和一個(gè)值,刪除數(shù)組中等于該值的元素并返回刪除后的數(shù)組大小,刪除操作必須在原數(shù)組中進(jìn)行,不允許我們另建一個(gè)數(shù)組。
該題目與上面的題目類似,不多說(shuō),上代碼

public class Solution {
    public int removeElement(int[] nums, int val) {
        
        int i = -1;  // 新數(shù)組最后一個(gè)元素的指針
        for(int j = 0; j < nums.length; j++)
        {
            if(nums[j] != val)
                nums[++i] = nums[j];
        }
        return i + 1;
    }
}
最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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