题:https://leetcode.com/problems/move-zeroes/submissions/1
题目
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.
题目大意
将数组 nums 中,所有 0 放在字符的尾部。
思路
设置指针 idx = 0 。
遍历 nums ,当 num 不为 0 ,将num放置在nums[idx]的位置,同时idx++。
若idx<nums.length 将 nums中 idx后的位置都置 为 0。
class Solution {
public void moveZeroes(int[] nums) {
int idx = 0;
for(int num : nums)
if(num != 0)
nums[idx++] = num;
while(idx<nums.length)
nums[idx++] = 0;
}
}