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

leetcode笔记:Move Zeroes

时间:2016-01-23 13:16:08      阅读:430      评论: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.

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.

二. 题目分析

题目的意思很明确,给定一个数组,将非零元素调整到前面,零元素放在数组后面,要求原位操作并使用尽量少的操作次数。

题目比较简单,只需扫描一次数组,在此过程中使用一个整形变量Index用于记录非零元素的个数,每遇到一个非零数,将其放在nums[Index]中,然后Index1

遍历一遍后,nums的非零元素位置已经确定,只需将数组后半段全部置零即可,由于Index记录了非零元素的个数,所以置零操作也很方便。

三. 示例代码

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        if (nums.size() < 1) return;  
        int Index = 0;
        for (int i = 0; i < nums.size(); ++i) 
            if (nums[i] != 0) 
                nums[Index++] = nums[i];

        for (;Index < nums.size(); ++Index) 
            nums[Index] = 0;
    }
};

四. 小结

对于这类问题,一般都要求原位操作及尽量少的操作次数。

leetcode笔记:Move Zeroes

标签:

原文地址:http://blog.csdn.net/liyuefeilong/article/details/50569118

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