leecode (8) - move zero
Mobile zero
Description:
Given an array of nums, write a function to move all zeros to the end of the array while maintaining the relative order of non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Explain:
- You must operate on the original array. You cannot copy additional arrays.
- Minimize the number of operations.
Train of thought:
According to the topic, we move the element whose value is not 0 forward and the element whose value is 0 to the back. An array element subscript can be set, initialized to 0, traversing the array from the front to the back. When an element with a value of 0 is encountered, it is exchanged with the element corresponding to the subscript initialized to 0, and then the subscript is added with 1. After traversing, we will move the element with a value of not 0 to the front, and the element with a value of 0 will naturally be placed at the back.
The code is as follows:
import java.util.Arrays; public class MoveZeroes { public static void moveZeroes(int[] nums) { if (nums == null || nums.length == 0 || nums.length == 1) { return ; } int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { int temp = nums[i]; nums[i] = nums[index]; nums[index++] = temp; } } } public static void main(String[] args) { int[] nums = {0,1,0,3,12}; moveZeroes(nums); System.out.println(Arrays.toString(nums)); } }
Another way of writing:
This method is similar to the one just written. All the non-zero elements in the array are assigned to the leading element bits of the array in order, and the rest are assigned to 0 directly. In fact, compared with the above, there is an operation of 0 assignment, which is not so simple. We suggest the first one (laugh with tears). But I wrote it myself. Record it. Ha ha.
import java.util.Arrays; public class MoveZeroes { public static void moveZeroes(int[] nums) { if (nums == null || nums.length == 0 || nums.length == 1) { return ; } int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { nums[index] = nums[i]; ++index; /* nums[index] = nums[i]; ++index; These two sentences can be abbreviated as: nums[index++] = nums[i]; Simplify a little */ } } for (int i = index; i < nums.length; i++) { nums[i] = 0; } } public static void main(String[] args) { int[] nums = {0,1,0,3,12}; moveZeroes(nums); System.out.println(Arrays.toString(nums)); } }