# 169 Majority Element
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
Was this helpful?