[LeetCode] 1089. Duplicate Zeros 復寫零



Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written.

Do the above modifications to the input array in place, do not return anything from your function.

Example 1:

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]

Note:

  1. 1 <= arr.length <= 10000
  2. 0 <= arr[i] <= 9

這道題給了一個數字數組,讓將每個0都復制一個,然后將數字右移一位,數組的長度還是保持不變,右移出范圍的數字就移除掉。這不是一道難題,比較直接的做法就是新建一個結果數組 res,然后遍歷給定數組 arr,for 循環條件加上一個 res 的長度小於n,將當前遍歷到的數字加入 res,然后判斷若當前數字是0,且此時 res 長度小於n,則再加個0到 res 中,最后把 arr 更新為 res 即可,參見代碼如下:


解法一:

class Solution {
public:
    void duplicateZeros(vector<int>& arr) {
        int n = arr.size();
        vector<int> res;
        for (int i = 0; i < n && res.size() < n; ++i) {
            res.push_back(arr[i]);
            if (arr[i] == 0 && res.size() < n) res.push_back(0);
        }
        arr = res;
    }
};

再來看一種雙指針的解法,這里還是用了一個額外數組 vec,初始時復制 arr 數組。用兩個指針i和j分別指向 arr 和 vec 數組,進行 while 循環,條件是i小於n,首先將 vec[j] 賦值給 arr[i],然后判斷若 arr[i] 是0,且 i+1 小於n,則i自增1后,將 arr[i] 賦值為0,然后i和j分別自增1,參見代碼如下:


解法二:

class Solution {
public:
    void duplicateZeros(vector<int>& arr) {
	vector<int> vec = arr;
        int i = 0, j = 0, n = arr.size();
        while (i < n) {
            arr[i] = vec[j];
            if (arr[i] == 0 && i + 1 < n) arr[++i] = 0;
            ++i; ++j;
        }
    }
};

下面來看一種不使用額外空間的解法,還是使用了雙指針來做,j初始化為 arr 數組的長度加上其中0的個數,實際上就是在不右移的情況下得到的新的數組的長度,i從 n-1 開始遍歷到0,首先對j進行自減1,若此時j小於n了,說明已經到需要更新的地方了,將 arr[j] 賦值為 arr[i],接下來處理0的情況,若 arr[i] 為0,且自減1后的j小於n,則將 arr[j] 賦值為0,還是不太理解整個過程的童鞋可以將例子1帶入,一步一步來嘗試運行,其實並不是很難理解,參見代碼如下:


解法三:

class Solution {
public:
    void duplicateZeros(vector<int>& arr) {
        int n = arr.size(), j = n + count(arr.begin(), arr.end(), 0);
        for (int i = n - 1; i >= 0; --i) {
            if (--j < n) arr[j] = arr[i];
            if (arr[i] == 0 && --j < n) arr[j] = 0;
        }
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1089


參考資料:

https://leetcode.com/problems/duplicate-zeros/

https://leetcode.com/problems/duplicate-zeros/discuss/312743/JavaC%2B%2B-O(n)-or-O(1)

https://leetcode.com/problems/duplicate-zeros/discuss/312727/C%2B%2BJava-Two-Pointers-Space-O(1)


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM