[Leetcode] 283. Move Zeroes
阿新 • • 發佈:2018-11-16
== write 一次 light The inpu relative 循環 ray
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.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
class Solution { // 把0移動到最後 <==> 把非0的移動到前面 public void moveZeroes(int[] nums) { // 記錄移動了一個非零元素到前面 // 當移動了move個非零元素到前面時,說明前move個都是移動過的,此時再往前移動時應放在 move位置,才不會破壞順序 int move = 0; // 記錄遍歷到第幾個 int index = 0; while (index < nums.length) { // 如果nums[index]!=0,說明它需要移動到move位置上,並且move+1 // 除了第一次循環以外,move位置的元素一定是0,因為循環到index時,遇到了move個非0,全移動到最前面了,所以move位置肯定是0 if (nums[index] != 0) { int temp = nums[move]; nums[move] = nums[index]; nums[index] = temp; move++; } index++; } } }
[Leetcode] 283. Move Zeroes