這個陣列是否包含任何元素 - Javascript


給定一個數字陣列,任何陣列元素將是該陣列中出現次數超過陣列長度一半的多數元素。

例如 -

如果陣列長度是 7,

那麼,如果陣列中出現任意元素 4 次或更多次,它將被視為多數。顯然任何特定陣列最多隻能有一個多數元素。

我們需要寫一個 JavaScript 函式,它以一個具有重複值數字陣列,如果陣列中存在多數元素,則返回 true。如果陣列中不存在這樣的元素,我們的函式應該返回 false。

示例

以下是程式碼 -

const arr = [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12];
const isMajority = arr => {
   let maxChar = -Infinity, maxCount = 1;
   // this loop determines the possible candidates for majorityElement
   for(let i = 0; i < arr.length; i++){
      if(maxChar !== arr[i]){
         if(maxCount === 1){
            maxChar = arr[i];
         }else{
            maxCount--;
         };
      }else{
         maxCount++;
      };
   };
   // this loop actually checks for the candidate to be the majority element
   const count = arr.reduce((acc, val) => maxChar===val ? ++acc : acc, 0);
   return count > arr.length / 2;
};
console.log(isMajority(arr));

輸出

會在控制檯產生以下輸出 -

true

更新時間: 30-Sep-2020

85 次瀏覽

開啟你的 職業 生涯

完成課程後獲得認證

開始
廣告