283. Move Zeroes Leetcode Java Solutin

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:

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

 

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         int pos = 0;
 4         for(int i =0; i< nums.length; i++){
 5             if(nums[i] != 0){
 6                 nums[pos++] = nums[i];
 7             }
 8         }
 9         for(;pos< nums.length; pos ++)
10             nums[pos] = 0;
11     }
12 }

 双指针压缩法。

posted @ 2016-04-11 20:43  Miller1991  阅读(92)  评论(0编辑  收藏  举报