2022-5-4 双指针
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
1 class Solution { 2 public void moveZeroes(int[] nums) { 3 int point=0,index=0; 4 while (point<nums.length){ 5 if (nums[point]!=0){ 6 nums[index]=nums[point]; 7 index++; 8 } 9 point++; 10 } 11 while (index<nums.length){ 12 nums[index]=0; 13 index++; 14 } 15 } 16 }
思路:先把非0的往前移动,后面再填充。
浙公网安备 33010602011771号