查詢和為給定值的三個數的 JavaScript 程式
我們將編寫一個 JavaScript 程式來查詢總和等於給定值的三個數。該程式將使用巢狀迴圈迭代輸入陣列,並檢查是否存在總和等於給定值的三個數。我們的程式將持續搜尋三個數,直到找到它或所有可能的組合都被窮盡。這個程式將使我們能夠高效且直接地找到總和等於給定值的三個數。
方法
查詢總和等於給定值的三個數的方法可以使用以下步驟實現:
將輸入陣列按升序排序。
迴圈遍歷陣列並固定一個元素。
初始化兩個指標,一個指向固定元素的下一個元素,另一個指向陣列的末尾。
檢查三個元素的總和是否等於給定值。
如果總和小於給定值,則遞增左指標。
如果總和大於給定值,則遞減右指標。重複此過程,直到找到三個數或指標交叉。
示例
給定一個整數陣列,我們想要找到總和等於給定值的三個數。這是一個解決此問題的 JavaScript 程式:
function findTriplet(arr, sum) {
// First, we sort the array in ascending order
arr.sort((a, b) => a - b);
// Next, we iterate through the array with the outer loop
for (let i = 0; i < arr.length - 2; i++) {
// We start the inner loop from i + 1 to avoid using the same number twice
let left = i + 1;
let right = arr.length - 1;
// The inner loop moves the left and right pointers towards each other
while (left < right) {
// If the sum of the current triplet is equal to the given sum, we have found our solution
if (arr[i] + arr[left] + arr[right] === sum) {
return [arr[i], arr[left], arr[right]];
}
// If the sum of the current triplet is less than the given sum, we need to increase the sum
// So, we move the left pointer to the right
else if (arr[i] + arr[left] + arr[right] < sum) {
left++;
}
// If the sum of the current triplet is greater than the given sum, we need to decrease the sum
// So, we move the right pointer to the left
else {
right--;
}
}
}
// If no triplet is found, we return null
return null;
}
// Example usage
let arr = [1, 4, 45, 6, 10, 8];
let sum = 22;
let triplet = findTriplet(arr, sum);
console.log(triplet);
解釋
函式 `findTriplet` 以陣列 `arr` 和一個總和作為引數。
首先,使用 `sort` 方法將陣列按升序排序。
接下來,我們使用 `for` 迴圈遍歷陣列,變數 `i` 從 0 到 `arr.length - 2`。
在外迴圈內,我們從 `i + 1` 開始內迴圈,以避免兩次使用相同的數字。兩個指標 `left` 和 `right` 分別初始化為 `i + 1` 和 `arr.length - 1`。
在內迴圈中,我們使用 `while` 迴圈不斷地將 `left` 和 `right` 指標相互移動,直到 `left` 小於 `right`。
在 `while` 迴圈內,我們檢查三個數 `arr[i] + arr[left] + arr[right]` 的當前總和。
如果它等於給定的 `sum`,我們找到了解決方案,並返回三個數 `[arr[i], arr[left], arr[right]]`。
如果它小於給定的 `sum`,我們需要增加總和,因此我們將 `left` 指標向右移動(遞增 `left`)。
如果它大於給定的 `sum`,我們需要減少總和。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP