[LeetCode] Move Zeroes 移動零


 

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

 

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

這道題讓我們將一個給定數組中所有的0都移到后面,把非零數前移,要求不能改變非零數的相對應的位置關系,而且不能拷貝額外的數組,那么只能用替換法in-place來做,需要用兩個指針,一個不停的向后掃,找到非零位置,然后和前面那個指針交換位置即可,參見下面的代碼:

 

解法一:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for (int i = 0, j = 0; i < nums.size(); ++i) {
            if (nums[i]) {
                swap(nums[i], nums[j++]);
            }
        }
    }
};

 

下面這種解法的思路跟上面的沒啥區別,寫法稍稍復雜了一點。。

 

解法二:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int left = 0, right = 0;
        while (right < nums.size()) {
            if (nums[right]) {
                swap(nums[left++], nums[right]);
            }
            ++right;
        }
    }
};

 

參考資料:

https://leetcode.com/discuss/59064/c-accepted-code

https://leetcode.com/discuss/70169/1ms-java-solution

 

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


免責聲明!

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



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