---
# System prepended metadata

title: 'Leetcode [No. 169] Majority Element(EASY)'
tags: [leetcode]

---

# Leetcode [No. 169] Majority Element(EASY)

## 題目

https://leetcode.com/problems/majority-element/

## 思路
+ 這個題目因為保證最多的數字會出現n/2次，所以只要用hashMap記錄每個出現的值，並且在判斷完後馬上return即可

```c++=
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int max_appears = floor(nums.size()/2);
        unordered_map<int,int> hashMap;
        for(int i = 0 ;i <nums.size(); i++)
        {
            hashMap[nums[i]]++;
            if(hashMap[nums[i]]>max_appears)
            {
                return nums[i];
            }
        }
        return -1;
    }
};
```

### 解法分析
+ time complexity: O(n)


### 執行結果

![image](https://hackmd.io/_uploads/ryzi-0R86.jpg)

## follow up:

> use linear time and O(1) space 


```C++=

```

### 解法分析

### 執行結果
