[LintCode] 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.

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

Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

 

LeetCode上的原题,请参见我之前的博客Move Zeroes

 

解法一:

复制代码
class Solution {
public:
    /**
     * @param nums an integer array
     * @return nothing, do this in-place
     */
    void moveZeroes(vector<int>& nums) {
        for (int i = 0, j = 0; i < nums.size(); ++i) {
            if (nums[i]) {
                swap(nums[i], nums[j++]);
            }
        }
    }
};
复制代码

 

解法二:

复制代码
class Solution {
public:
    /**
     * @param nums an integer array
     * @return nothing, do this in-place
     */
    void moveZeroes(vector<int>& nums) {
        int left = 0, right = 0;
        while (right < nums.size()) {
            if (nums[right]) {
                swap(nums[left++], nums[right]);
            }
            ++right;
        }
    }
};
复制代码

 

 

posted @   Grandyang  阅读(827)  评论(0)    收藏  举报
编辑推荐:
· dotnet 9 通过 AppHostRelativeDotNet 指定自定义的运行时路径
· 如何统计不同电话号码的个数?—位图法
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
阅读排行:
· 用c#从头写一个AI agent,实现企业内部自然语言数据统计分析
· 三维装箱问题(3D Bin Packing Problem, 3D-BPP)
· Windows上,10分钟构建一个本地知识库
· dotnet 9 通过 AppHostRelativeDotNet 指定自定义的运行时路径
· 使用 AOT 编译保护 .NET 核心逻辑,同时支持第三方扩展
Fork me on GitHub

喜欢请打赏

扫描二维码打赏

Venmo 打赏

点击右上角即可分享
微信分享提示