Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
题目链接:https://leetcode.com/problems/move-zeroes/submissions/
题目分析:非0的往前放,后面不足的补0
0ms,时间击败100%
class Solution {
public void moveZeroes(int[] nums) {
int pos = 0, i = 0;
while (i < nums.length) {
if (nums[i] != 0) {
nums[pos++] = nums[i];
}
i++;
}
while (pos < nums.length) {
nums[pos++] = 0;
}
}
}