1. 程式人生 > >【Leetcode】從排序陣列中刪除重複元素

【Leetcode】從排序陣列中刪除重複元素

  • 題目:給定一個排序的陣列,刪除重複的位置,使每個元素只顯示一次並返回新的長度

不要為另一個數組分配額外的空間,您必須使用常量記憶體來進行此操作。

例如,
給定輸入陣列nums = [1,1,2],

您的函式應返回長度= 2,與前兩個元素NUMS是1和2分別

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. Subscribe to see which companies asked this question.

//思路:遍歷一遍陣列
//用兩個指標,當元素重複時,跳過重複的位置,當不重複的時候,把元素放到正確的位置上去 int removeDuplicates(vector<int>& nums) { int temp = nums[0]; int size = 0; for (int i = 0; i < nums.size();) { while (temp == nums[i]) { i++; } if (size == 0)//為什麼不直接從1開始,因為有可能元素個數為0,很可能造成陣列越界,但是放在迴圈裡面又需要每次進行判斷,那有沒有更優的解法呢?
{ size++; } if (size != i) { nums[size++] = nums[i++]; } } return size; }

幾種更優的解法:
<一>

int removeDuplicates(vector<int>& nums) {
    int i = 0;
    for (int n : nums)
        if (!i || n > nums[i-1])
            nums[i++] = n;
    return i;
}

<二>

And to not need the !i check in the loop:

int removeDuplicates(vector<int>& nums) {
    int i = !nums.empty();
    for (int n : nums)
        if (n > nums[i-1])
            nums[i++] = n;
    return i;
}