283.[圖解]Move Zeroes

1.題目描述

來源:LeetCode

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.

給入一個含有數字的陣列,寫出一個 function 將所有的 0 都移到陣列的最後面,但同時須保持所有其他非零數字的相對先後順序不變。

2.題目解析
看到陣列換數字的時候都會想到雙指針,用雙指針的方式(x,y),指向兩個不同的位置,主要是判斷y是否遇到0,當y遇到0時交換兩個指針的值。覺得和
Remove Duplicates from Sorted Array遇到的雙指針很像。

3.畫流程圖

4.程式碼

5.上傳LeetCode的結果

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.