
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1: 输入: nums = [0,1,0,3,12] 输出: [1,3,12,0,0] 示例 2: 输入: nums = [0] 输出: [0]2.解题思路
双指针解法:
定义两个整型变量left与right作为左指针与右指针.
左指针指向处理好的序列的尾部,每次移动1位
右指针指向待处理的序列的头部,每次移动到非零处
左右指针交换.
3.解法双指针:
class Solution {
public void moveZeroes(int[] nums) {
int len = nums.length;
int left = 0;
int right = 0;
while(right < len){
if (nums[right] != 0){
// 右指针不等于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;
}
}
4.技能点
双指针解法.