zoukankan      html  css  js  c++  java
  • [LeetCode] 283. Move Zeroes

    Description

    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:

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

    Analyse

    将一个数组里所有的0移到非0值得右边,不打乱非0值得顺序

    关键在于in-place,不能申请额外的内存空间

    遍历vector,用非0值覆盖0值就行了,用一个index记录当前写到vector的哪个位置了

    void moveZeroes(vector<int>& nums) {
        int len = nums.size();
        int current_not_zero_index = 0;
        int nonzero_count = 0;
        for (int i = 0; i < len; i++) {
            if (nums[i] == 0) {
                continue;
            } else {
                ++nonzero_count;
                nums[current_not_zero_index++] = nums[i];
            }
        }
    
        for (int j = nonzero_count; j < len; j++) {
            nums[j] = 0;
        }
    }
    

    下面的代码是Leetcode上最快的解法,使用了remove来移除vector中的0值

    void moveZeroes(vector<int>& nums) {
        ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
        int n1 = nums.size();
        vector <int>::iterator pos;
        pos = remove (nums.begin(), nums.end() , 0); // 指向未被remove元素的后面一个元素的
        for(auto i = pos; i != nums.end(); ++i)
            *i = 0;
    }
    

    下面介绍remove(),功能和我上面写的代码差不多

    template <class ForwardIterator, class T>
      ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val)
    {
      ForwardIterator result = first;
      while (first!=last) {
        if (!(*first == val)) { // 只有值不为val的元素才会被添加到result中
          *result = *first;
          ++result;
        }
        ++first;
      }
      return result;
    }
    

    remove的返回值是 指向最后一个未被remove元素的后面一个元素的迭代器,在这里是指向第一个0的迭代器

    An iterator to the element that follows the last element not removed.
    The range between first and this iterator includes all the elements in the sequence that do not compare equal to val.

    举例说明remove函数的处理过程

    输入:        [0,1,0,3,12]
                  [0,1,0,3,12]  // 遍历到input[0]
                  [1,1,0,3,12]  // 遍历到input[1]
                  [1,1,0,3,12]  // 遍历到input[2]
                  [1,3,0,3,12]  // 遍历到input[3]
                  [1,3,12,3,12] // 遍历到input[4]
    remove后输出:[1,3,12,3,12]
    

    Reference

    1. remove - C++ Reference
  • 相关阅读:
    Spring Boot发布2.6.2、2.5.8:升级log4j2到2.17.0
    如何优雅地读写HttpServletRequest和HttpServletResponse的请求体
    更快的Maven来了
    Spring Cloud Gateway过滤器精确控制异常返回(实战,控制http返回码和message字段)
    NumPy学习笔记
    来自Java程序员的Python新手入门小结
    Java应用日志如何与Jaeger的trace关联
    Jaeger知识点补充
    分布式调用链跟踪工具Jaeger?两分钟极速体验
    Spring Cloud Gateway过滤器精确控制异常返回(实战,完全定制返回body)
  • 原文地址:https://www.cnblogs.com/arcsinw/p/12680834.html
Copyright © 2011-2022 走看看