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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
 1 public class Solution {
 2     public void MoveZeroes(int[] nums) {
 3         int i = 0, j = 0;
 4         
 5         while (j < nums.Length)
 6         {
 7             if (nums[j] != 0)
 8             {
 9                 if (i != j)
10                 {
11                     var tmp = nums[i];
12                     nums[i] = nums[j];
13                     nums[j] = tmp;
14                 }
15                 
16                 i++;
17             }
18             
19             j++;
20         }
21     }
22 }

 

posted @ 2017-12-07 04:16  逸朵  阅读(93)  评论(0)    收藏  举报