zoukankan      html  css  js  c++  java
  • LeetCode(283): Move Zeros

    Move Zeros: 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.

    题意:移除给定数组中的0元素,将0元素移动到数组的末尾,并且保持不是0元素的元素的顺序。

    思路: 可以利用一个指针将不是0 的元素尽可能的往前排,然后将剩余的全部设置为0。

    代码:

    public void moveZeroes(int[] nums) {
            int cnt =0,pos = 0;
            int len = nums.length;
    
            for(int i =0;i<len;i++){
                //非0元素向前移
                if(nums[i]!=0){
                    nums[pos] = nums[i];
                    pos++;
                }
            }
            //其余元素设置为0
            for(;pos<len;pos++){
                nums[pos]= 0;
            }
        }
  • 相关阅读:
    自定义函数
    内置函数
    炸裂函数explode
    -bash:ls:command not found,执行命令总是报找不到
    函数
    C#的lock用法
    获取客户端Ip地址方法
    Grunt基础
    常用Sql
    HandleBars
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5107761.html
Copyright © 2011-2022 走看看