# Majority Element

<https://leetcode.com/problems/majority-element/description/>

> 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.

## Thoughts

因为最多元素比总数一半还多，也就是把这个元素看成+1, 其它看成-1, 总和会是正的。利用此思想每遇到和target相同的+1, 否则-1，当为负时就把当前换成target。任何一个不是解的target都会被冲为负，遇到解后会一直保持正数直到结束。

## Code

```
/*
 * @lc app=leetcode id=169 lang=cpp
 *
 * [169] Majority Element
 */
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        const int N = nums.size();
        if (N == 1) return nums[0];
        if (N == 0) return 0;
        int count = 1, target = nums[0];
        for (int i = 1; i < N; ++i) {
            if (target != nums[i]) --count;
            else ++count;
            if (count < 0) {
                target = nums[i];
                count = 0;
            }  
        } 
        return target;
    }
};


```

## Analysis

时间O(N), 空间O(1)


---

# 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://hao-fu-1.gitbook.io/oj/math/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.
