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;
            }
        }
    }
    
  • 相关阅读:
    26.angularJS $routeProvider
    25.内置API
    24.路由
    iOS开发网络篇—数据安全
    从idea到ipo
    CentOS下php安装mcrypt扩展
    iOS客户端学习之AES加密
    PHP 标准AES加密算法类
    使用php扩展mcrypt实现AES加密
    base64的作用
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10703185.html
Copyright © 2011-2022 走看看