原題:https://leetcode.com/problems/move-zeroes/git
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.github
Example:this
Input: Output: [0,1,0,3,12][1,3,12,0,0]
Note:code
//我是想作一個交換 將0日後移 public static void moveZeroes(int[] nums) { int length =nums.length; int count= 0; LOOP:for (int i = 0;i<length;i++){ if(nums[i] == 0){ count = i+1; if(count == length){ break LOOP; } while(nums[count] == 0){ count ++; if(count == length){ break LOOP; } } int temp = nums[count]; nums[count] = nums[i]; nums[i] = temp; } } System.out.println(Arrays.toString(nums)); } //可是看到不少人提交 都是將非0 往前移動 public static void moveZeroes2(int[] nums) { if (nums == null || nums.length == 0) { return; } int insertPos = 0; for (int num: nums) { if (num != 0) { nums[insertPos++] = num; } } while (insertPos < nums.length) { nums[insertPos++] = 0; } } //簡化一下 public static void moveZeroes3(int[] nums) { //慢一點走的j int j = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; j++; } System.out.println(Arrays.toString(nums)); } }
git:https://github.com/woshiyexinjie/leetcode-xinelement