zoukankan      html  css  js  c++  java
  • lintcode539

    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
    Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
    Notice
    1. You must do this in-place without making a copy of the array.
    2. Minimize the total number of operations.

    转换思路,swap的时候不是想着把零都移到最后面去(这种思路会让非零数相对位置变乱),而是把非零数挪到前面连续非零数的尾端。因为要保持非零数的相对位置,所以想到不能用相向双指针,而应该是同向双指针。

    双指针。O(n)
    中间状态是:一串非零数,一串零,一串未知。
    i标定已处理范围,[0, i)下标的内容都是非零的。(开括号是因为一开始不知道第一个位置是不是0)
    j遍历指针,在找到一个非零对象时,与i对象互换,让非零串增长。从而可以i++j++
    遍历逻辑:j指0时,只加j。j指非0时,swap,加i,加j。 

    类似题目: Remove Duplicates from Sorted Array。 https://www.cnblogs.com/jasminemzy/p/9704494.html

    实现:

    class Solution {
        public void moveZeroes(int[] nums) {
            int i = 0, j = 0;
            while (i < nums.length && j < nums.length) {
                if (nums[j] == 0) {
                    j++;
                } else {
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                    i++;
                    j++;
                }
            }
        }
    }
  • 相关阅读:
    commons-logging.jar 和 log4j.jar 的关系
    百钱买百鸡
    reflect
    golang结构体、接口、反射
    golang文件操作
    sqlx使用说明
    go example
    goroutine
    生成二维码
    method&interface
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9479214.html
Copyright © 2011-2022 走看看