개발일지/TIL

[leetcode] 169. Majority Element

JangKroed 2023. 8. 23. 23:46
728x90
반응형

Majority Element

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

 

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2

 

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

 

풀이 - 1

요소의 최대값이 제일 큰 요소를 반환하는 문제로 Object를 이용하여 풀이하였다.

function majorityElement(nums: number[]): number {
  const obj: { [key: number]: number } = {};

  for (let i = 0; i < nums.length; i++) {
    !obj[nums[i]] ? (obj[nums[i]] = 1) : obj[nums[i]]++;
  }

  let maxKey: number = 0;
  let maxValue: number = 0;

  for (const key in obj) {
    if (!maxKey && !maxValue) {
      maxKey = Number(key);
      maxValue = obj[key];
      continue;
    }

    if (obj[key] > maxValue) {
      maxKey = Number(key);
      maxValue = obj[key];
    }
  }

  return maxKey;
}

최대한 반복문 한번만 사용하는 방법을 생각해보려했으나 실패했다. (테스트는 통과)

728x90
반응형