自己的
思路是双指针,右指针用来找非零元素,找到后赋值给左指针,保证左指针的左面都是非零元素。遍历到最后,让左指针本身和右边全为零即可
class Solution {
public void moveZeroes(int[] nums) {
int i = 0;
int j = 0;
while(j < nums.length){
if(nums[j] != 0){
nums[i] = nums[j];
i ++;
}
j ++;
}
for(;i < nums.length; 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;
}
}
同样是双指针解法,但官方用了交换元素
标签:right,nums,int,指针,++,283,移动,left From: https://www.cnblogs.com/lmc7/p/18095868