博主并没有什么算法基础,所以写的不好,勿喷,抛砖引玉,欢迎交流,感谢。
//给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
// 示例:
// 输入: [0,1,0,3,12]
//输出: [1,3,12,0,0]
// 说明:
// 必须在原数组上操作,不能拷贝额外的数组。
// 尽量减少操作次数。
// Related Topics 数组 双指针
// 👍 736 👎 0
package com.zqh.leetcode.editor.cn;
import java.util.Arrays;
//Java:移动零
public class P283MoveZeroes {
public static void main(String[] args) {
Solution solution = new P283MoveZeroes().new Solution();
int array[] = new int[]{0, 1, 0, 3, 12};
solution.moveZeroes(array);
System.out.println(Arrays.toString(array));
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
continue;
}
nums[j++] = nums[i];
}
while (j < nums.length) {
nums[j] = 0;
j++;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}