leetcode 283. 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.

Example:

Input: [0,1,0,3,12]
Output: [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.

 

解法一:我的解法

最原始的解法  only beats 15% 呜呜

class Solution {
    public void moveZeroes(int[] nums) {
        int l = nums.length;
        int c = 0, i = 0;
        while (i < l - c) {
            if(nums[i] == 0) {
                for(int j = i; j < l-1; j++) {
                    nums[j] = nums[j+1];
                }
                nums[l-1] = 0;
                c++;
            }else{
                i++;
            }
        }
    }
}

 

解法二:pointer

直接用一个指针p来指向不含0的数组进程。遍历原数组,将非零的数存入原数组的p位置。

O(n)

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null || nums.length == 0) return;
        
        int p = 0;
        for(int num: nums){
            if(num != 0) nums[p++] = num;
        }
        while(p < nums.length) {
            nums[p++] = 0;
        }
    }
}

 

posted @ 2019-02-26 21:02  JamieLiu  阅读(104)  评论(0编辑  收藏  举报