> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/ladder_code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/ladder_code/ms/majority-element-ii.md).

# Majority Element II

Given an integer array of size n, find all elements that appear more than `⌊ n/3 ⌋` times.

**Note:** The algorithm should run in linear time and in O(1) space.

**Example 1:**

```
Input: [3,2,3]
Output: [3]
```

**Example 2:**

```
Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
```

分析

求出现频率超过1/3的数字

可以每次出现3组数的时候就减掉Triple,这样抵消到最后。剩余的数字算算有没全局的1/3

这里注意dict相减法，和直接set（dict）得到所有unique key

```
collections.Counter(set(cnt))
```

```
class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        cnt = collections.Counter()
        for i in nums:
            cnt[i] += 1
            if len(cnt) == 3:
                cnt -= collections.Counter(set(cnt))
        return [n for n in cnt if nums.count(n) > int(len(nums) / 3)]
        
```


---

# 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 dynamically by asking a question.

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

```
GET https://nataliekung.gitbook.io/ladder_code/ms/majority-element-ii.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.
