[LeetCode] #283 移动零
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
先放非零数,再放零
class Solution { public void moveZeroes(int[] nums) { int index = 0,count = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] != 0) nums[index++] = nums[i]; else count++; } for(int i = nums.length-1; i > nums.length-count-1; i--) nums[i]=0; } }
双指针,零于非零交换
class Solution { public void moveZeroes(int[] nums) { int n = nums.length, left = 0, right = 0; while (right < n) { if (nums[right] != 0) { swap(nums, left, right); left++; } right++; } } public void swap(int[] nums, int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } }
知识点:无
总结:无