Leetcode 283. Move Zeroes
public class Solution {
public void moveZeroes(int[] nums) {
int j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=0){
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
j++;
}
}
}
}
follow up: minimize writes 代码只需要返回最后有效数组的长度,有效长度之外的数字是什么无所谓,原先input里面的数字不一定要保持原来的相对顺序
int moveZeroesWithMinimumSetps(vector<int>& nums)
{
int left = 0, right = nums.size() - 1;
while (left < right)
{
while (left < right && nums[left] != 0)left++;.
while (left < right && nums[right] == 0)right--;
if (left < right)nums[left++] = nums[right--];
}
return left;
}