LeetCode:Move Zeroes - 將數組中的0移到最後

一、題目名稱java

Move Zeroes(將數組中的0移到最後)數組

二、題目地址函數

https://leetcode.com/problems/move-zeroescode

三、題目內容element

英文: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.leetcode

中文:給出一個數字數組,寫一個函數將數組中全部的0移動到非0項的後面開發

例如:給出數組 nums  = [0, 1, 0, 3, 12] ,調用完函數後,數組元素的順序會變爲 [1, 3, 12, 0, 0]。get

注意:1)不能複製一個新數組;2)你須要最小化對數字的操做次數。it

四、解題方法io

完成本題須要下面兩個步驟

1)將非0數字依次向前移動

2)將後面空出的部分所有補0

實現此方法的Java代碼以下:

/**
 * 功能說明:LeetCode 283 - Move Zeros
 * 開發人員:Tsybius2014
 * 開發時間:2015年9月20日
 */
public class Solution {
    
    /**
     * 將數字0移動到最後
     * @param nums 輸入數組
     */
    public void moveZeroes(int[] nums) {
        
        //將非0數字向前挪
        int cur = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[cur] = nums[i];
                cur++;
            }
        }

        //後面的元素所有補0
        for (int i = cur; i < nums.length; i++) {
            nums[i] = 0;
        }
    }
}

END

相關文章
相關標籤/搜索