leetCode-Move Zeroes

Posted kevincong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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对应的元素交换就可以了

版权声明:本文为博主原创文章,未经博主允许不得转载。


以上是关于leetCode-Move Zeroes的主要内容,如果未能解决你的问题,请参考以下文章

283. (Move Zeroes)移动零

Leetcode | Move Zeroes

Move Zeroes (算法)

Leetcode:Move Zeroes

Move Zeroes

LeetCode-- 73. Set Matrix Zeroes