> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/169.-majority-element-easy.md). Agents can also search and read this documentation through its [MCP server](https://jenhsuan.gitbook.io/algorithm/~gitbook/mcp).

# 169. Majority Element (Easy)

## 1.問題

* 給予一個大小為n的array, 找出出現次數大於一半的成員

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LIF1R2AIAsSOzkYqZMI%2F-LIKQNsSDbw6Rs04Nc9O%2F2018072603.jpg?alt=media\&token=e14369c4-755a-43a0-ae13-9450144ac48e)

## 2.想法

* 用多個vector儲存數字所出現的次數, 如果次數出現數量超過一半則回傳該數字

## 3.程式碼

```
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int, int> cnt;
        for(int i = 0; i < nums.size(); i++)
        {
            cnt[nums[i]]++;
            if (cnt[nums[i]] > nums.size()/2)
            {
                return nums[i];
            }
        }
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LIF1R2AIAsSOzkYqZMI%2F-LIKQqoB128l5K25ZjWm%2F2018072604.jpg?alt=media\&token=fda87d6f-793d-4ee6-bebb-4f16c24257bc)
