zoukankan      html  css  js  c++  java
  • 283. Move Zeroes(把数组中的 0 移到末尾)

    iven 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]

    方法一:新开辟一个数组存储,比较简单,不列了。
    方法二:移位(记录0的个数)
    class Solution {
        public static void moveZeroes(int[] nums) {
            int n=nums.length;
            int [] order=new int[n];int count=0;
            for(int i=0;i<n;i++){
                if(nums[i]==0){
                    count++; 
                }
                if(nums[i]!=0&&count!=0){
                    nums[i-count]=nums[i];
                    nums[i]=0;
                }
            }
    
        }
    }

    方法三:移位(记录新数组的个数)

    class Solution {
        public static void moveZeroes(int[] nums) {
            int n=nums.length;
            int [] order=new int[n];
            int index=0;
            for(int i=0;i<n;i++){
                if(nums[i]!=0){
                    nums[index++]=nums[i];
                }
            }
            for(int i=index;i<n;i++){
                nums[index++]=0;
            }
    
        }
    苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
  • 相关阅读:
    quickSort
    L1-3 宇宙无敌加法器
    deepin下用命令管理自己的Github仓库
    PAT 1008
    增量包算法,时间复杂度3n
    vue组件化-容器
    vue模块化设计
    语言语法糖Sugar
    虚拟dom节点,支持querySelector
    html语法树转html
  • 原文地址:https://www.cnblogs.com/shaer/p/10864581.html
Copyright © 2011-2022 走看看