[Leetcode] Move Zeroes, leetcodezeroes
Move Zeroes questions:
Given an arraynums, Write a function to move all0'S to the end of it while maintaining the relative order of the non-zero elements.
For example, givennums = [0, 1, 0, 3, 12], After calling your function,numsShocould be[1, 3, 12, 0, 0].
Note:
The idea at the beginning was to traverse the array, move it back when it encounters 0, and keep moving the last step. The Code is as follows:
public class Solution { public static void moveZeroes(int[] nums) { for (int i = 0; i < nums.length; i++) { if (nums[i] == 0 && i != (nums.length - 1)) { for (int j = i; j < nums.length - 1; j++) { int temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } } }}
However, the 001 test case is incorrect.
Well, I found the problem, because the first number is 0, and the second 0 cannot be moved to the end.
In another way, instead of looking for 0 through traversal, we traverse to find non-0. If it is not 0 and is not in the first place, we will move forward until it is not 0.
public class Solution { public static void moveZeroes(int[] nums) { for (int i = 0; i < nums.length; i++) { if (nums[i] != 0 && i != 0) { for (int j = i; j > 0 && nums[j - 1] == 0; j--) { int temp = nums[j - 1]; nums[j - 1] = nums[j]; nums[j] = temp; } } } }}
This solves the problem.
Other methods
public static void moveZeroes(int[] nums) { int i = 0, j = 0; for (i = 0; i < nums.length; i++) { if (nums[i] != 0) { if (j != i) { nums[j] = nums[i]; nums[j] = 0; } j++; } } }
In this method, I traverses the array. Only when I points to a non-zero and ji is different, j is moved back and the number at j is changed to the number at I, and set the number at I to 0 and ij to synchronize and move backward. When I points to 0, only I moves backward and j still points to 0.
There is also a simpler method
public void moveZeroes(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; }}