标签:
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:
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
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 }
标签:
原文地址:http://www.cnblogs.com/sherry900105/p/4929144.html