JavaScript 中至少包含兩個元素的子陣和


問題

我們需要編寫一個 JavaScript 函式,其中第一個引數是包含整數的陣列 arr,第二個引數是單個整數 target。我們的函式應檢查是否存在大小至少為 2 的連續子陣列,其和為 k 的倍數,即和為 n*k,其中 n 可以是任意整數。

如果存在,則返回 true,否則返回 false。

例如,如果函式的輸入是 -

const arr = [23, 2, 6, 4, 7];
const target = 6;

則輸出應為 -

const output = true;

輸出說明

因為 [23, 2, 6, 4, 7] 是大小為 5 的連續子陣列,且和為 42。

示例

程式碼如下 -

 現場演示

const arr = [23, 2, 6, 4, 7];
const target = 6;
const checkSubarraySum = (arr = [], target = 1) => {
   let sum = 0
   const hash = {}
   hash[0] = -1;
   for (let i = 0; i<arr.length; i++) {
      sum += arr[i]
      if (target!=0) sum %= target
      if ( hash[sum] !== undefined ) {
         if(i-hash[sum]>1) return true
      } else {
         hash[sum] = i
      }
   };
   return false;
};
console.log(checkSubarraySum(arr, target));

輸出

控制檯中的輸出將為 -

true

更新於:03-Mar-2021

133 次瀏覽

開啟您的職業生涯

完成教程認證

開始
廣告