zoukankan      html  css  js  c++  java
  • 8.Move Zeroes(移动零)

    Level:

      Easy

    题目描述:

    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.

    思路分析:

      根据题目要求,不能使用额外的空间,并且当移动零后其他元素的相对位置不变,我们可以在遍历数组的过程中,将不为0的元素,重新填充在原数组中,以index=0为下标开始,遇到一个不为0的元素,index加1。遍历完整个数组,然后从index开始,将index到数组尾部的所有元素都置为0,就得到了最终的结果。

    代码:

    class Solution {
        public void moveZeroes(int[] nums) {
            int index=0;
            for(int i=0;i<nums.length;i++){
                if(nums[i]!=0)
                    nums[index++]=nums[i];
            }
            for(int j=index;j<nums.length;j++){
                nums[j]=0;
            }
        }
    }
    
  • 相关阅读:
    Oracle 基础系列之1.3 用户管理
    Oracle 系统常用命令
    Gogs安装
    centos7 Minimal安装没有ifconfig
    centos 上安装nodejs v8.0.0
    Linux 学习笔记
    使用 weinre 远程调试移动端页面
    Linux tree命令
    innodb分区
    Innodb表空间
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10703185.html
Copyright © 2011-2022 走看看