Leetcode283. 移动0

题目

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

C++代码

#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int i = -1, j = -1;
        int size = (int)nums.size();
        while (++j < size) {
            if (nums[j]!=0) nums[++i] = nums[j];
        }
        while (++i < size && (nums[i] = 0) == 0);
    }
};

int main(int argc, const char * argv[]) {
    // insert code here...
    vector<int> vec {0,1,0,3,12};
    Solution solution;
    solution.moveZeroes(vec);
    for (auto item: vec) cout << item << " "; cout << endl;
    vec = {2, 1};
    solution.moveZeroes(vec);
    for (auto item: vec) cout << item << " "; cout << endl;
    return 0;
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容