zoukankan      html  css  js  c++  java
  • 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++;
                }
            }
        }
    };

  • 相关阅读:
    vue模拟接口数据
    修改placeholder的颜色
    network is unreachable mongodb
    数字转时间
    前端下载流文件
    jquery的AJAX中各个事件执行顺序
    移动端谨慎使用overflow:hidden
    时间函数整理
    background-size使用时的注意点
    关于iframe
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5408835.html
Copyright © 2011-2022 走看看