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

    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 元素, 统统拖到数组末尾。


    思路:

    两个指针start,  i 从index为0的位置出发。

    指针 i 用来扫数组,若 i 对应的元素非 0 时,

    直接将指针 i 对应元素赋值给指针 start 对应元素,同时 start++。

    这样,指针 i 遍历完毕数组,指针 start 也将所有非0元素保存在数组了 index [0 ~ i] 的位置

    最后将数组的后半部分都赋值为 0。


    代码:

    class Solution {
        public void moveZeroes(int[] nums) {
            int start = 0;
            for(int i = 0; i < nums.length; i++){
                if(nums[i] != 0){
                    nums[start] = nums[i];
                    start++; 
                }   
            }       
            for(int i = start; i< nums.length; i++){
                nums[i] = 0;
            }
        }
    }
  • 相关阅读:
    <BackTracking> dfs: 39 40
    <Tree> 110 124
    <Tree.PreOrder> DFS 113, 129
    <Math> 50 367
    <String> 49 87
    Haproxy配置Rabbitmq集群负载均衡
    Rabbitmq镜像集群的搭建
    rabbitmq常用命令
    Linux安装rabbitmq
    Docker自定义网络
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9059077.html
Copyright © 2011-2022 走看看