今天刷了兩題,有夠上進~值得吃薯條慶祝!

題目

Given an integer array nums, move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2:

Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

Follow up: Could you minimize the total number of operations done?

解題

這題很簡單,自信心++
將給定陣列的0往最後面放即可~

我是先將值為零的元素從陣列刪除,然後計數器加一,再跑一次迴圈把零補上。
不過後來想到,刪掉時同時補上也行,就不用再多一個while迴圈了。

class Solution {

    /**
     * @param Integer[] $nums
     * @return NULL
     */
    function moveZeroes(&$nums) {
        $i = 0;
        foreach($nums as $key => $val) {
            if($nums[$key] == 0) {
                unset($nums[$key]);
                $i++;
            }
        }
                    
        while($i > 0) {
            $nums[] = 0;
            $i--;
        }
    }
}

Runtime: 12 ms, faster than 81.89% of PHP online submissions for Move Zeroes.

Memory Usage: 17 MB, less than 25.20% of PHP online submissions for Move Zeroes.