1. 程式人生 > >[LeetCode] Move Zeroes

[LeetCode] 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.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations

題意:把陣列的零移到末尾,其餘元素相對位置不變,不能使用新陣列,讓操作次數儘可能小。

思路:用到一個佇列,從前向後列舉,每當遇到一個零,向佇列裡新增這個零元素的位置,每當遇到非零元素,看是否佇列不為空,不為空的話就取出一個元素,把這個非零元素放在從佇列裡取出來的對應位置上,然後把這個非零元素的位置加入佇列,並把這個位置的元素改為零。

C程式碼:

void moveZeroes(int* nums, int numsSize) {
    int head,tail;
    head = tail = 0;
    int i,pos[10005];
    for(i = 0; i < numsSize; i++) {
        if(nums[i] == 0) {
            pos[tail++] = i;
        }
        else if(head <4 tail) {
            pos[tail++] = i;
            nums[pos[head]] = nums[i];
            head++;
            nums[i] = 0;
        }
    }
}

Java程式碼:

public class Solution {
	public void moveZeroes(int[] nums) {
		int head,tail,i,len;
		int[] queue = new int[20005];
		len = nums.length;
		head = tail = 0;
		for(i = 0; i < len; i++) {
			if(nums[i] == 0) {
				queue[tail++] = i;
			}
			else if(head < tail){
				queue[tail++] = i;
				nums[queue[head]] = nums[i];
				head++;
				nums[i] = 0;
			}
		}
    }
}