zoukankan      html  css  js  c++  java
  • LC.283.Move Zeroes

    https://leetcode.com/problems/move-zeroes/description/
    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:
    You must do this in-place without making a copy of the array.
    Minimize the total number of operations.

     1 //normal way of doing it:time: O(n) space: O(1)
     2     public void moveZeroes(int[] nums) {
     3         //corner cases:
     4         if(nums == null || nums.length == 0) return ;
     5         //two pointers: i: non-zero index-slow  j: normal index counter-faster
     6         int i =0, j = 0 ;
     7         while(j<nums.length){
     8             if (nums[j]==0){
     9                 j++;
    10             }else{
    11                 nums[i] = nums[j] ;
    12                 i++ ;
    13                 j++;
    14             }
    15         }
    16         /*
    17         * add all the trailing 0: tricky part is from i or from i+1?
    18         * in this case, we could use some example to help
    19         * [0 1 0 0  2]  [ 1 2 000] i =2, so we should use i to length
    20          * */
    21         for (int k = i; k < nums.length ; k++) {
    22             nums[k] = 0 ;
    23         }
    24     }

     

     1 /*
     2     this is used for the case lots of zero:
     3     time complexity: 2(swap) * # of non-zero  ~ o(#of non-zero)
     4     * */
     5     public void moveZeros2(int[] nums){
     6         //corner cases:
     7         if(nums == null || nums.length == 0) return ;
     8         //two pointers: i: (-inf, i) non-zero, i is the 1st index zero (slow)  j: normal index counter-faster
     9         int i =0, j =0 ;
    10         while (j<nums.length){
    11             //when j is non-zero, swap with i
    12             if (nums[j] != 0){
    13                 int temp = nums[j] ;
    14                 nums[j] = nums[i]; //i is the 1st index zero
    15                 nums[i] = temp;
    16                 i++;
    17             }
    18             j++;
    19         }
    20     }

     

  • 相关阅读:
    用Python实现谷歌的小恐龙游戏
    nyoj_187_快速查找素数_201312042102
    nyoj_218_Dinner_201312021434
    nyoj_66_分数拆分_201312012122
    nyoj_524_A-B Problem_201312012035
    hdu_2054_A == B_201311301601
    nyoj_655_光棍的yy_201311281539
    nyoj_111_分数加减法_201311281341
    nyoj_60_谁获得了最高奖学金_201311281117
    nyoj_264_国王的魔镜_201311271800
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8553329.html
Copyright © 2011-2022 走看看