leetCode-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.

My Solution:

class Solution {
    public void moveZeroes(int[] nums) {
        int j = 0, len = nums.length;
        for(int i = 0;i < len;i++){
           if(nums[i] != 0){
               nums[j++] = nums[i];
           }
        }
        for(int i = j;i<len;i++){
            nums[i] = 0;
        }
    }
}

Another Better Solution:

class Solution {
    public void moveZeroes(int[] nums) {
        int j = 0, len = nums.length;
        for(int i = 0;i < len;i++){
           if(nums[i] != 0){
           int temp = nums[j];
               nums[j++] = nums[i];
               nums[i] = temp;
           }
        }
    }
}

总结:
用一个指针j表示非零元素的位置,注意和i对应的元素交换就可以了

版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:https://www.cnblogs.com/kevincong/p/7881334.html