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.

二. 题目分析

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

题目比较简单,只需扫描一次数组,在此过程中使用一个整形变量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,Algorithm,C++,算法,inplace)