publicvoidmoveZeroes(int[] nums){ int index = 0; for (int num : nums) { if (num != 0) { nums[index++] = num; } } for (int i = index; i < nums.length; ++i) { nums[i] = 0; } } }
也可以采用交换的方法把非零元素往前移。
这样最后就不用单独赋零值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclass{
publicvoidmoveZeroes(int[] nums){ int index = 0; for (int i = 0; i < nums.length; ++i) { if (nums[i] != 0) { swap(nums, index++, i); } } }
privatevoidswap(int[] nums, int i, int j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
近期评论