寫在前面
此係列來源於開源項目:前端 100 問:能搞懂 80%的請把簡歷給我
爲了備戰 2021 春招
每天一題,督促自己
從多方面多角度總結答案,豐富知識
週一算法題之「移動零」
簡書整合地址:前端 100 問
正文回答
題目
給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說明:
- 必須在原數組上操作,不能拷貝額外的數組。
- 儘量減少操作次數。
代碼
function zeroMove(array) {
let len = array.length;
let j = 0;
for (let i = 0; i < len - j; i++) {
if (array[i] === 0) {
array.push(0);
array.splice(i, 1);
i--;
j++;
}
}
return array;
}
function moveZeroToLast(arr) {
let index = 0;
for (let i = 0, length = arr.length; i < length; i++) {
if (arr[i] === 0) {
index++;
} else if (index !== 0) {
arr[i - index] = arr[i];
arr[i] = 0;
}
}
return arr;
}
// 雙指針法
function moveZero(nums) {
let i = 0;
for (let j = 0; j < nums.length; j++) {
if (nums[j] !== 0) {
// * nums[j]不等於0,i必進一
if (nums[i] === 0) {
// * 如果nums[i]等於0了,則交換,否則只進一
let temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
i++;
}
}
return nums;
}
let nums = [0, 1, 0, 3, 12];
let nums1 = [1, 2, 0, 4, 3];
let nums2 = [1, 0, 0, 4, 3];
console.log(moveZero(nums));
console.log(moveZero(nums1));
console.log(moveZero(nums2));