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.

链接: http://leetcode.com/problems/move-zeroes/

3/7/2017

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         if (nums.length == 0) return;
 4         int i = 0, j = 0, count = 0;
 5         while (j < nums.length) {
 6             if (nums[j] == 0) {
 7                 j++;
 8                 count++;
 9                 continue;
10             }
11             if (count > 0) nums[i] = nums[j];
12             i++;
13             j++;
14         }
15         while (i < nums.length) {
16             nums[i++] = 0;
17         }        
18     }
19 }

别人的算法更加简洁,大致上是一样的。

4/16/2017

BB电面准备

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         if (nums == null || nums.length == 0) return; 
 4         int i = 0;
 5         for (int j = 0; j < nums.length; j++) {
 6             if (nums[j] == 0) continue;
 7             else {
 8                 if (i == j) {
 9                     i++; 
10                     continue;
11                 }
12                 nums[i++] = nums[j];
13             }
14         }
15         while (i < nums.length) nums[i++] = 0;
16         return;
17     }
18 }

 

posted @ 2017-03-08 02:57  panini  阅读(122)  评论(0编辑  收藏  举报