238.移动零Java
题目描述
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
输入输出样式
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
本题来自LeetCode:https://leetcode-cn.com/problems/move-zeroes/
思路
使用双指针left, right扫描,right扫描到非零的元素就把left覆盖同时left往前,直到right走到尾部。
算法分析
时间复杂度O(n),空间复杂度为O(1)
求解函数
class Solution {
public void moveZeroes(int[] nums) {
int left = 0, right = 0;
while (right != nums.length) {
if (nums[right] != 0) {
nums[left++] = nums[right];
}
++right;
}
//把剩下的元素都置零
for (int i = left; i < nums.length; ++i) {
nums[i] = 0;
}
}
}