在 JavaScript 中找出兩個陣列中的最大值
問題
我們要求編寫一個 JavaScript 函式,該函式採用兩個包含表示兩個數字的單個數字的陣列作為其第一個和第二個引數,arr1 和 arr2。函式的第三個引數將是一個數字,
num (num <= length of arr1 + length of arr2)
我們的函式應返回一個長度為 num 的單個數字陣列,它本身代表一個數字。並且該數字應該是使用兩個陣列中的元素能夠建立的最大數字,我們的唯一條件是必須保持相同陣列中元素的相對順序。
例如,如果輸入函式的是 -
const arr1 = [1, 3, 4, 5, 6]; const arr2 = [9, 1, 2, 5, 8, 3]; const num = 4;
那麼輸出應該是 -
const output = [9, 8, 6, 3];
例子
此程式碼將是 -
const arr1 = [1, 3, 4, 5, 6];
const arr2 = [9, 1, 2, 5, 8, 3];
const num = 4;
const maxArray = (arr1 = [], arr2 = [], num) => {
const map = new Map();
const match = (a, b, num) => {
if (map.has(a + ',' + b + ',' + num)) {
return map.get(a + ',' + b + ',' + num);
}
let output = [];
while(num > 0) {
let maxa = -Infinity;
let maxai = 0;
let maxb = -Infinity;
let maxbi = 0;
for(let i = a; i < arr1.length && arr1.length + arr2.length - (i + b) >= num; i++) {
if (arr1[i] > maxa) {
maxa = arr1[i];
maxai = i;
}
}
for(let i = b; i < arr2.length && arr1.length + arr2.length - (a + i) >= num; i++) {
if (arr2[i] > maxb) {
maxb = arr2[i];
maxbi = i;
}
}
if (maxa === maxb) {
output.push(maxa);
let ca = map.get(a+','+(maxbi+1)+','+(num-1)) || match(a, maxbi+1, num-1);
let cb = map.get((maxai+1)+','+b+','+(num-1)) || match(maxai+1,b,num-1);
map.set(a+','+(maxbi+1)+','+(num-1), ca);
map.set((maxai+1)+','+b+','+(num-1), cb);
if (ca.join('') > cb.join('')) {
return [...output, ...ca];
} else {
return [...output, ...cb];
}
} else if (maxa > maxb) {
output.push(maxa);
a = maxai + 1;
} else {
output.push(maxb);
b = maxbi + 1;
}
num--;
}
map.set(a + ',' + b + ',' + num, output);
return output;
}
return match(0, 0, num);
};
console.log(maxArray(arr1, arr2, num));程式碼說明
我們採取的步驟是 –
使用 for 迴圈,直到剩餘的 num 允許它繼續。
如果 arr1 比 arr2 具有較高的數字,則我們首先使用 arr1 數字,否則我們使用 arr2 數字。
當 arr1 和 arr2 具有相同的數字,直到允許 for 迴圈繼續時,我們僅使用遞迴來比較兩個值,並選擇較大的數字。
輸出
控制檯中的輸出將是 -
[ 9, 8, 6, 3 ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP