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

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    不知道怎么就地操作

    [一句话思路]:

    用一个指针来控制,就能实现就地操作

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 没有理解:0是while最后一起添加的

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    全是0可以最后一起添加

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    单个指针,实现就地

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    27. Remove Element

     [代码风格] :

    class Solution {
        public void moveZeroes(int[] nums) {
            //cc
            if (nums == null || nums.length == 0) return;
            //ini
            int insertPos = 0;
     
            for (int num : nums) {
                //no 0s
                if (num != 0) {
                    nums[insertPos++] = num;
                }
            }
             //0s
                while (insertPos < nums.length) {
                    nums[insertPos++] = 0;
                }
            //return
        }
    }
    View Code
  • 相关阅读:
    java_十进制数转换为二进制,八进制,十六进制数的算法
    vim常用命令 vim键盘布局
    百度HTTPS加密搜索有什么用?
    delete
    hadoop2的automatic HA+Federation+Yarn配置的教程
    MinGW GCC下sleep()函数问题
    delete
    8天学通MongoDB——第一天 基础入门
    8天学通MongoDB——第六天 分片技术
    8天学通MongoDB——第五天 主从复制
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8835888.html
Copyright © 2011-2022 走看看