【LeetCode 283】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.

Example:

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

Note:

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

代碼

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

爲什麼別人家的代碼總是能這麼簡潔。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章