leetcodeの旅(7)-Move Zeroes


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.

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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

考え方:


本当のことを言う。うなずくのが大きいのを見たばかりで、後ろに書いてみて、考えはすべての要素を遍歴して、0なら、後ろの要素を前に1つ移動して、それからゼロを後ろに移動します。


注意:ループの時、急いでループ変数に1を加えないで、移動後、0かどうかを判断してください。ゼロの場合は移動し、1を加算しません。また移動するたびに、後ろにゼロを追加し、変数count技術を設定し、後ろにn=n-countをループします。


コード:

public class Solution {
    public void moveZeroes(int[] nums) {
        int n = nums.length;
        //             
        int num = n;
        int i = 0;
        while(i < num){
            if(nums[i] == 0){
                int last = nums[i];
                for(int a = i;a < n-1;a++){
                    nums[a] = nums[a+1];
                }
                nums[n-1] = last;
            }
            if(nums[i] != 0){
            //     ,    1
                i = i+1;
            }else{
            //      ,        
                num = num-1;
            }
        }
    }
}