[LeetCode]283. Move Zeroes

移动0

Posted by JinFei on August 17, 2021

题目描述

Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example1:

Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]

Example2:

Input: nums = [0] Output: [0]

Constraints:

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Follow up:

  • Could you minimize the total number of operations done?

解题思路:

  • 一个变量,记录0的位置,如果当nums[i]不为0的话,就让他与前面的0进行交换

Solution

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int cnt = 0;
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] != 0){
                swap(nums[i], nums[cnt++]);
            }
        }
    }
};