https://leetcode.cn/problems/move-zeroes/?envType=study-plan-v2&envId=programming-skills
思路:
1.在原数组上直接操作,采用双指针的思想,每次移动r,当r不为0时交换num中的值
class Solution {public void moveZeroes(int[] nums) {int n = nums.length;int l = 0,r = 0;while(r < n) {if(nums[r]!=0) {swap(nums,l,r);l++;}r++;}}public static void swap(int[]nums,int l,int r) {int t = nums[l];nums[l] = nums[r];nums[r] = t;}
}
执行时间:2ms 内存:44.9MB
直接开辟新的数组,遍历原数组时将不为0的元素存入新数组,最后补0即可
class Solution {public void moveZeroes(int[] nums) {int n = nums.length;int[] k = new int[n];int m = 0;for(int i = 0;i<n;i++) {if(nums[i]!=0) {k[m] = nums[i];m++;}}//在末尾补0for(int i = 0;i<n-m;i++) {k[m+i]=0;}for(int i =0;i<n;i++) {nums[i] = k[i];}}
}
执行时间 :1ms 内存:44.8MB