輸入 [1,8,9]
輸出 [[1],[1,8],[1,8,9],[8],[8,9],[9]]
它看起來像子集陣列,但我想用兩個指標的方式得到這個輸出。假設 leftP=0,rightP=0;然后通過使用 for 回圈,rightP 將增加到陣列的末尾,直到沒有更多元素,然后 leftP 移動 1 ...
1 -> [1], [1,8],[1,8,9]
8 -> [8],[8,9]
9 -> [9]
function solution(arr) {
let totalArr = [];
let leftP = 0;
for(let rightP=0; rightP<arr.length; rightP ) {
totalArr.push(arr[rightP]);
// this is where i'm kinda stuck
while()
}
}
uj5u.com熱心網友回復:
您只需使用 2 個 for 回圈即可輕松實作這一點,因為您正在執行以下操作:
i在這里leftP,j在這里rightP
const arr = [1, 8, 9];
const result = [];
for (let i = 0; i < arr.length; i) {
let temp = [arr[i]];
result.push([...temp]);
for (let j = i 1; j < arr.length; j) {
temp.push(arr[j]);
result.push([...temp]);
}
temp = [];
}
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
只需使用兩個指標對陣列進行切片!
下面的作業解決方案:
const arr = [1, 8, 9];
const solution = (arr) => {
const resArr = [];
for (let i = 0; i < arr.length; i ) {
for (let j = i 1; j <= arr.length; j ) {
resArr.push(arr.slice(i, j));
}
}
return resArr;
};
console.log(solution(arr));
uj5u.com熱心網友回復:
我只是將您的邏輯轉換為代碼,注意您將需要兩個嵌套回圈。
function solution(arr) {
let totalArr = [];
for (let left = 0; left < arr.length; left ) {
totalArr.push([]);
for (let right = left 1; right <= arr.length; right ) {
totalArr[left].push(arr.slice(left, right));
}
}
return totalArr;
}
console.log(JSON.stringify(solution([1, 8, 9])));
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
(請注意,這基于left- 對它們進行分組以使陣列平坦):
function solution(arr) {
let totalArr = [];
for (let left = 0; left < arr.length; left ) {
for (let right = left 1; right <= arr.length; right ) {
totalArr.push(arr.slice(left, right));
}
}
return totalArr;
}
console.log(JSON.stringify(solution([1, 8, 9])));
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386029.html
標籤:javascript 数组
