diff --git a/Week_01/jqb/P283MoveZeroes.java b/Week_01/jqb/P283MoveZeroes.java new file mode 100644 index 0000000000000000000000000000000000000000..d0ebac3f36e37178efffbd7af2e0b6623d64e01c --- /dev/null +++ b/Week_01/jqb/P283MoveZeroes.java @@ -0,0 +1,66 @@ +//给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 +// +// 示例: +// +// 输入: [0,1,0,3,12] +//输出: [1,3,12,0,0] +// +// 说明: +// +// +// 必须在原数组上操作,不能拷贝额外的数组。 +// 尽量减少操作次数。 +// +// Related Topics 数组 双指针 +// 👍 882 👎 0 + +package homework.algorithm.Week_01.jqb; + +import java.util.Arrays; + +//Java:移动零 +public class P283MoveZeroes { + public static void main(String[] args) { + Solution solution = new P283MoveZeroes().new Solution(); + // TO TEST + int[] nums = new int[] {1,1,1,3,0,12,0,0}; + solution.moveZeroesSolution1(nums); + System.out.println(Arrays.toString(nums)); + } + //leetcode submit region begin(Prohibit modification and deletion) +class Solution { + public void moveZeroesSolution1(int[] nums) { + + // 1、Shift non-zero values as far forward as possible + // 2、Fill remaining space with zeros + if (nums == null || nums.length == 0) { + return; + } + int insertPos = 0; + for (int i = 0; i < nums.length ; i++) { + if(nums[i] != 0) { + nums[insertPos++] = nums[i]; + } + } + while (insertPos < nums.length) { + nums[insertPos++] = 0; + } + + } + public void moveZeroesSolution2(int[] nums) { + 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++; + } + } + } + + + } +//leetcode submit region end(Prohibit modification and deletion) + +}