LeetCode移动零
LeetCode移動零
給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾 ,同時保持非零元素的相對順序。
說明:
- 必須在原數組上操作 ,不能拷貝額外的數組。
- 盡量減少操作次數。
void moveZeroes(int* nums, int numsSize){ int count = 0, length = numsSize-1; while (length >= 0) { if(nums[length] == 0) { count++;//計數 int temp = length; while (temp < numsSize-1) { nums[temp] = nums[temp+1]; temp++; } } length--; } while (count >0) { nums[numsSize-count] = 0; count--; }}官方答案 :雙指針法
思路及解法
使用雙指針 ,左指針指向當前已經處理好的序列的尾部 ,右指針指向待處理序列的頭部 。
右指針不斷向右移動 ,每次右指針指向非零數 ,則將左右指針對應的數交換 ,同時左指針右移。
注意到以下性質:
左指針左邊均為非零數;
右指針左邊直到左指針處均為零