> For the complete documentation index, see [llms.txt](https://leetcodebook-1.gitbook.io/top-interview-150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leetcodebook-1.gitbook.io/top-interview-150/array-string/majority-element.md).

# 多数元素

### 题目地址

题目链接: <https://leetcode.cn/problems/majority-element/>

## 解题思路

### 思路一(排序)

1. 多数元素是指出现的次数大于n/2的元素，因此排序后，第n/2位置的元素必然是多数

### 答案一

```go
func majorityElement(nums []int) int {
    sort.Ints(nums)
    return nums[len(nums)/2]
}
```

### 思路二(统计)

1. 循环遍历数组，统计每个元素的个数
2. 遍历统计结果，判断元素个数是否大于n/2
3. 若大于则为多数

### 答案二

```go
func majorityElement(nums []int) int {
    countMap := map[int]int{}
    for _,item:=range nums{
        countMap[item]+=1
    }
    for key,value:=range countMap{
        if value>len(nums)/2{
            return key
        }
    }
    return 0
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://leetcodebook-1.gitbook.io/top-interview-150/array-string/majority-element.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
