# 169 Majority Element

LeetCode

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

input: 一個數字陣列
output: 找出主要出現的那個數字,那個數字出現出量一定大於 n /2
Example 1:

Input: [3,2,3]
Output: 3
Example 2:

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

*/

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {}

怎麼解

雖然解出來效率很不佳,不過其實我還蠻開心我已經懂得換位思考了。題目有一個關鍵是答案數量 > n /2,所以我可以排序之後找中間那個值就是答案了 !

var majorityElement = function(nums) {
    nums.sort((a, b) => a - b)
    let mid = Math.floor(nums.length / 2);
    return nums[mid];
};

console.log(majorityElement([2,2,1,1,1,2,2]))
// faster than 31.92% of JavaScript online submissions

Last updated