JavaScript 中乘積剛好小於目標值的子陣列
問題
我們需要編寫一個 JavaScript 函式,該函式將第一個引數視為數字陣列 arr,第二個引數視為數字 target。
我們的函式應該統計和返回(連續)子陣列的數量,其中子陣列中所有元素的乘積小於目標值。
例如,如果函式的輸入是
輸入
const arr = [10, 5, 2, 6]; const target = 100;
輸出
const output = 8;
輸出解釋
乘積小於 100 的 8 個子陣列是 −
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
請注意,[10, 5, 2] 沒有包括在內,因為 100 的乘積不嚴格小於 k。
示例
以下是程式碼 −
const arr = [10, 5, 2, 6];
const target = 100;
const countSubarrays = (arr = [], target = 1) => {
let product = 1
let left = 0
let count = 0
for (let right = 0; right < arr.length; right++) {
product *= arr[right]
while (left <= right && product >= target) {
product /= arr[left]
left += 1
}
count += right - left + 1
}
return count
};
console.log(countSubarrays(arr, target));輸出
8
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP