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便往后面移动并不影响算法。

  • 相关阅读:
    Powershell分支条件
    Powershell基础
    初识PowerShell
    设计模式--策略模式
    设计模式--简单工程模式
    StandardWrapper
    Tomcat的安全性
    算法效率 简单的增长率 参照

    排序算法之 归并排序
  • 原文地址:https://www.cnblogs.com/MrSaver/p/5902093.html
Copyright © 2011-2022 走看看