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

    Question:

    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.

    Analysis:

    问题描述:给出一个数组,写一个函数是数组中所有的0移到最后,并且保持其他的数字的顺序不变。

    注意,不能额外申请一个数组。最小化额外操作数的数目。

    思路:做一次for循环,每当遇到一个0时,与和他距离最近的一个不为0的数交换,T(n) = O(n).

    Answer:

    public class Solution {
        public void moveZeroes(int[] nums) {
            for(int i=0; i<nums.length - 1; i++) {
                    if(nums[i] == 0) {
                        int j = i + 1;
                        while(nums[j] == 0 && j<nums.length - 1)
                            j++;
                        nums[i] = nums[j];
                        nums[j] = 0;
                        if(j == nums.length - 1) //如果一直遍历到了最后,则说明后面的全部是0,可以结束循环了
                            i = nums.length - 1;
                    }
            }
        }
    }
  • 相关阅读:
    体温上报系统
    Android开发概述和开发工具
    体温上报系统
    CSS padding(填充)
    CSS margin外边距实例
    CSS margin(外边距)
    CSS轮廓outline
    函数对象与闭包
    作业,3.19名称空间作用域
    名称空间/作用域
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4821977.html
Copyright © 2011-2022 走看看