• 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.

    解答:在处理这个题的时候想到了快排中一遍扫描的过程,利用两个变量i和j,分别来控制0的边界和非0的边界。故而可以得到如下的代码:

    代码:

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

  • 相关阅读:
    php 压缩文件 zip
    php 创建返回结果配置文件 实例
    php 生成xml文件
    php 获取读取文件内容
    基于JAVA语言的多线程技术
    Java HTTP请求
    TCP与UDP
    VC6.0 调试.dll文件
    [JNI] Java 调用 C++ dll
    HTTPS与SSL
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5408835.html
Copyright © 2020-2023  润新知