LeetCode*26. Remove Duplicates from Sorted Array

LeetCode題目鏈接

題目:

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.

答案一(利用容器):

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int ns = nums.size();
        if (ns == 0) {
            return 0;
        }
        int i = 0;
        while (i < ns - 1) {
            if (nums[i] == nums[i + 1]) {
                nums.erase(nums.begin() + i + 1);
                ns--;
            } else {
                i++;
            }
        }
        
        return ns;
    }
};

答案二(Java):

雙指針。直接改變數(shù)組,當(dāng)出現(xiàn)重復(fù)的數(shù)的時候,跳過;當(dāng)數(shù)不重復(fù)時,賦值給較慢的指針,最終的結(jié)果是數(shù)組前面一部分沒有重復(fù)的值,后面的數(shù)字無意義,由于會返回數(shù)組的大小。因此還是可以區(qū)分。

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        
        int i = 0;
        for (int j = 1; j < nums.length; j++) {
            if (nums[i] != nums[j]) {
                i++;
                nums[i] = nums[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)容