283. Move Zeroes - LeetCode
阿新 • • 發佈:2018-08-06
圖片 class http rt+ lse lee img cloud tco
Question
283. Move Zeroes
Solution
題目大意:將0移到最後
思路:
1. 數組復制
2. 不用數組復制
Java實現:
數組復制
public void moveZeroes(int[] nums) { int[] arr = Arrays.copyOf(nums, nums.length); int start = 0; int end = nums.length - 1; for (int i=0; i<arr.length; i++) { int tmp = arr[i]; if (tmp == 0) { nums[end--] = 0; } else { nums[start++] = tmp; } } }
不用數組復制
public void moveZeroes(int[] nums) { int start = 0; int zeroCount = 0; for (int i=0; i<nums.length; i++) { int tmp = nums[i]; if (tmp == 0) { zeroCount++; } else { nums[start++] = tmp; } } for (int i = 0; i < zeroCount; i++) { nums[nums.length - 1 - i] = 0; } }
283. Move Zeroes - LeetCode