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

LeetCode:Move Zeroes

时间:2016-09-24 00:38:11      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

LeetCode: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.

【优质算法】

public class Solution {
    public void moveZeroes(int[] nums) {
        int index=0;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]!=0)
                nums[index++]=nums[i];
        }
        while(index<nums.length)
            nums[index++]=0;
    }
}

【题后反思】

  这里也有双指针的应用,index是一个慢指针,i代表一个快指针,i不断向后移动,并判断所在位置元素是否为0,如果为0的话,就往后移动;如果不为0的话,让index等于这个值,这里是最关键的一步,在这里index起到从头开始更新这个数组的作用,把所有的的非0数字更新到数组中,忽略的0很可能就在更新中被赋予新的值。所以元素为0便往后面移动并不影响算法。

LeetCode:Move Zeroes

标签:

原文地址:http://www.cnblogs.com/MrSaver/p/5902093.html

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