我正在研究我在 leetcode 的討論部分中看到的這個解決方案,但我無法掌握部分邏輯。游戲的名稱是將所有零移動到給定陣列的末尾,同時保持其他數字的順序。j 索引內的增量運算子是我丟失的地方,因為它不會將非零數字放在右側嗎?
var moveZeroes = function(nums) {
let j = 0
for(let i = 0; i < nums.length; i ) {
if(nums[i] !== 0) {
//storing the index we are iterating on
let n = nums[i]
//changing the index in place to 0
nums[i] = 0
//console.log(nums);
//
nums[j ] = n
console.log(nums);
}
}
return nums;
};
console.log(moveZeroes([0,1,0,3,12]));
uj5u.com熱心網友回復:
請記住,j 是后遞增的,因此 j 的初始值用于索引 nums,然后 j 遞增。如果是 j,則 j 將首先遞增,然后使用。
uj5u.com熱心網友回復:
嘗試使用Array.filter()將零(例如num === 0)和非零數字(例如num !== 0)分成兩個新的單獨陣列。然后使用Array.concat()或展開運算子將它們合并為一個陣列。
詳細資訊在下面的代碼中注釋
// log() is an optional utility function that formats console logs
const log = data => console.log(`[${data}]`);
// This input array has zeroes everywhere
const numbers = [0, 1, 0, 0, 3, 0, 12];
const moveZeroes = array => {
// With the given array called "numbers"
// left = [1, 3, 13]
const left = array.filter(num => num !== 0);
// right = [0, 0, 0, 0]
const right = array.filter(num => num === 0);
// Then arrays "left" and "right" are merged
return [].concat(left, right)
};
log(moveZeroes(numbers));
uj5u.com熱心網友回復:
只需洗掉所有零。將洗掉的零添加到末尾。
var moveZeroes = (nums) =>
(
nums.toString().replaceAll("0,", "")
",0".repeat(("" nums).replace(/[^0]/g, "").length)
)
.split(",")
.map(Number);
console.log(moveZeroes([0, 1, 0, 0, 3, 0, 12])); //[ 1, 3, 12, 0, 0, 0, 0 ]
筆記:
("" nums).replace(/[^0]/g,'').length: 陣列中 0 的數量nums.toString(): 要將陣列轉換為我們使用的字串,或者我們可以使用連接空字串的技巧,例如"" numssplit(','): 將字串轉換為陣列map(Number): 將字串陣列轉換為數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359112.html
標籤:javascript 数组 算法 数据结构
上一篇:演算法問題:尋找最便宜的航班
