# # 169 Majority Element

[LeetCode](https://leetcode.com/problems/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
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hannahpun.gitbook.io/leetcode-note/array/169-majority-element.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
