zoukankan      html  css  js  c++  java
  • LeetCode:Move Zeroes

    LeetCode: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.

    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.

    【优质算法】

    public 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];
            }
            while(index<nums.length)
                nums[index++]=0;
        }
    }

    【题后反思】

      这里也有双指针的应用,index是一个慢指针,i代表一个快指针,i不断向后移动,并判断所在位置元素是否为0,如果为0的话,就往后移动;如果不为0的话,让index等于这个值,这里是最关键的一步,在这里index起到从头开始更新这个数组的作用,把所有的的非0数字更新到数组中,忽略的0很可能就在更新中被赋予新的值。所以元素为0便往后面移动并不影响算法。

  • 相关阅读:
    【zookeeper】
    关于redis-windows环境下的一些配置:
    mybatis-注解开发
    jQuery的Validate插件
    Thymeleaf 学习笔记-实例demo(中文教程)
    thymeleaf 学习笔记-基础篇(中文教程)
    AGC 043C
    JOISC 2020 部分题解
    Loj #2687
    CF 1270I
  • 原文地址:https://www.cnblogs.com/MrSaver/p/5902093.html
Copyright © 2011-2022 走看看