Leetcode 283:Move Zeroes
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.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
题目解析:
对数组进行操作的题。
需要有一个index来作为维护的指针,一个count来计算数组中有多少个0。
使用一个for循序遍历数组,然后判断当前位置是否为0:
1. 为0,count++
2. 不为0,将值重新填入index位,index++
当循环结束的时候,将所有的0填入index之后的所有位置上。
1 public void moveZeroes(int[] nums) { 2 int count = 0; 3 int index = 0; 4 for(int i = 0; i < nums.length; i++){ 5 if(nums[i] == 0){ 6 count++; 7 }else{ 8 nums[index] = nums[i]; 9 index++; 10 } 11 } 12 for(int k = 1; k <= count; k++){ 13 nums[k + index - 1] = 0; 14 } 15 }