码迷,mamicode.com
首页 > 其他好文 > 详细

Move Zeroes

时间:2016-05-28 20:32:31      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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.

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

要求在O(n) 的时间复杂完成。不需要额外的空间。

思路:从头遍历数组找到第一个为0的元素,纪录其下标为i. 在i的右边找到第一个不为0的元素记录其下标为j。交换nums[i] 与 nums[j]. 从j + 1 开始继续寻找不为0的元素,当j等于数组的长度时,表明0的元素都移动到了数组的尾部。

        注意 交换了之后 i + 1 ~ j 之间的元素一定都是0的元素。

 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 || nums.length == 1) {
 8             return;
 9         }
10         int i = 0;
11         for (i = 0; i < nums.length; i++) {
12             if (nums[i] == 0) {
13                 break;
14             }
15         }
16         if (i == nums.length) {
17             return;
18         }
19         
20         for (int j = i + 1; j < nums.length; j++) {
21             if (nums[j] != 0) {
22                 int temp = nums[i];
23                 nums[i] = nums[j];
24                 nums[j] = temp;
25                 i = i + 1;
26             }
27         }
28         return;
29     }
30 
31 }

 

Move Zeroes

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5538175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!