Move zero
Title description: Given an array
nums
, write a function to move all0
to the end of the array while maintaining the relative order of non-zero elements.Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/move-zeroes/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: array traversal
First, declare a variable theLastNotZeroPos to record the last non-zero position, and then traverse the array nums from back to front. If the elements of the array are equal to 0, the following processing is required:
- If the current position is equal to theLastNotZeroPos, then decrease theLastNotZeroPos by one and continue to traverse the next element;
- If the current position is not equal to theLastNotZeroPos, move all the elements from the last position to theLastNotZeroPos forward by one position, and then change the element at theLastNotZeroPos position to 0, and reduce theLastNotZeroPos by one, and then process the next element.
After the traversal is completed, it is the result of the movement.
public class LeetCode_283 {
public static void moveZeroes(int[] nums) {
// 最后一个非0的位置
int theLastNotZeroPos = nums.length - 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] == 0) {
if (i != theLastNotZeroPos) {
for (int j = i; j < theLastNotZeroPos; j++) {
nums[j] = nums[j + 1];
}
nums[theLastNotZeroPos] = 0;
}
theLastNotZeroPos--;
}
}
}
public static void main(String[] args) {
int[] nums = new int[]{0, 1, 0, 3, 12};
System.out.println("-----移动前-----");
for (int num : nums) {
System.out.print(num + " ");
}
System.out.println();
moveZeroes(nums);
System.out.println("-----移动后-----");
for (int num : nums) {
System.out.print(num + " ");
}
}
}
[Daily Message] The uncertainty of life is the source of our hope.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。