Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript 다수 요소가 있는 배열을 확인하고 동일한 배열에 있으면 TRUE를 반환합니다.

<시간/>

반복적인 값을 가진 숫자 배열을 가져와 (n/2)번 이상 나타나는 숫자를 반환하는 JavaScript 함수를 작성해야 합니다. 여기서 n은 배열의 길이입니다. 배열에 그러한 요소가 없으면 함수는 false를 반환해야 합니다.

이 함수에 대한 코드를 작성해 봅시다 -

예시

const arr = [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12];
const arr1 = [3, 565, 7, 23, 87, 23, 3, 65, 1, 3, 6, 7];
const findMajority = 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];
         } 0else {
            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(findMajority(arr));
console.log(findMajority(arr1));

출력

콘솔의 출력은 -

true
false