Command Palette

Search for a command to run...

Command Palette

Search for a command to run...

Majority Element

Find the element that appears more than n/2 times using sorting approach

Find the element that appears more than half the time in an array

問題描述

給定一個大小為 n 的數組 nums,返回其中的多數元素。多數元素是指在數組中出現次數 大於 ⌊n/2⌋ 的元素。

你可以假設數組是非空的,並且給定的數組總是存在多數元素。

範例

輸入:nums = [3,2,3]
輸出:3

輸入:nums = [2,2,1,1,1,2,2]
輸出:2

限制條件

解題思路

解決方案

export function majorityElement(nums: number[]): number {
  // Sort and take the middle value as the majority element
  // Since majority element appears > n/2 times, the middle value after sorting is guaranteed to be it
  const midIndex = Math.floor(nums.length / 2);
  const sortedNums = nums.toSorted((a, b) => a - b);
 
  return sortedNums[midIndex];
}

相關題目