leetcode [#283]

目录

题目

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:
given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public void moveZeroes(int[] nums) {
int N = 0;
for(int k = 0;k < nums.length; k++){
if(nums[k] == 0){
N++;
continue;
} else {
if(N > 0){
nums[k-N] = nums[k];
nums[k] = 0;
}
}
}
}
}

注意事项

  1. 遍历一遍数组,遇到0,就给零值计数器加一。
  2. 遇到非零,如果前面至少有一个零(N>1),则将当前值前移N位,并给当前位赋值为0。