LeetCode283移動零問題java高效解法

一、題目:

給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。 
示例:
  輸入: [0,1,0,3,12]
  輸出: [1,3,12,0,0]
說明:
  1.必須在原數組上操作,不能拷貝額外的數組。
  2.盡量減少操作次數。

二、思路:

分為兩種情況:
  1.第一位(即L指針指的地方為0):當R指針所指數字為0時,R指針右移;否則交換左右指針位置,左右指針同時右移;
  2.第一位不為0:同理,當R指針為0時,L指針右移,否則首先左指針右移,再交換位置,右指針右移.

三、程式碼實現:

class Solution {
    public void moveZeroes(int[] nums) {
        int L = 0;
        int R = 1;
        while (R <= nums.length - 1){
            if (nums[L] == 0){
                if (nums[R] == 0){
                    R++;
                }else {
                    int temp = nums[L];
                    nums[L] = nums[R];
                    nums[R] = temp;
                    R++;
                    L++;
                }
            }else {
                if (nums[R] == 0) {
                    R++;
                } else {
                    L++;
                    int temp = nums[L];
                    nums[L] = nums[R];
                    nums[R] = temp;
                    R++;
                }
            }
        }
    }
}

 

運行效果: