https://leetcode-cn.com/problems/move-zeroes/
一 题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例: 输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明: 必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
二 题解
class Solution {public void moveZeroes(int[] nums) {int length = nums.length;int zeroTag = 0;// 找到第一个为0的位置while(zeroTag<length){if(nums[zeroTag]==0){break;}zeroTag++;}int positiveTag = zeroTag;while(positiveTag<length){if(nums[positiveTag]!=0){nums[zeroTag] = nums[positiveTag];nums[positiveTag] = 0;zeroTag ++;}positiveTag++;}}}
三 题解二
对于数组 nums 取一个指针index,指向数组头部,即index = 0;
遍历数组,如果遍历的值不为0,则赋值给数组 index 位置,并将index指针后移,即 index++;
如果遍历的值为0,则继续下一轮遍历。
一轮遍历过后,便将数组中不为0的数放于数组 index位置之前。
最后再对 index及之后的位置赋值 0 。
class Solution {public void moveZeroes(int[] nums) {int index = 0;for (int num : nums) {if (num != 0) {nums[index++] = num;}}for (int i = index; i < nums.length; i++) {nums[i] = 0;}}}
