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.

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

Given nums = [0, 1, 0, 3, 12], after calling your function,nums should be [1, 3, 12, 0, 0].

分析:

用一个指针 p 指向第一个元素,从第一个元素开始,如果当前元素nums[i]不是0,那么就和nums[p]互换位置,然后p++. 这里千万不能从尾部开始,否则不能保证order一致。

 1 public class Solution {
 2     /**
 3      * @param nums an integer array
 4      * @return nothing, do this in-place
 5      */
 6     public void moveZeroes(int[] nums) {
 7         if (nums == null || nums.length == 0) return;
 8         int start = 0;
 9         for (int i = 0; i < nums.length; i++) {
10             if (nums[i] != 0) {
11                 swap(nums, i, start);
12                 start++;
13             } 
14         }
15     }
16     
17     public void swap(int[] arr, int idx1, int idx2) {
18         int temp = arr[idx1];
19         arr[idx1] = arr[idx2];
20         arr[idx2] = temp;
21     }
22 }

 

posted @ 2016-07-11 21:39  北叶青藤  阅读(167)  评论(0编辑  收藏  举报