> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/bu-chong-4060-dao/169.-majority-element-wei-yun-suan.md).

# 169. Majority Element(位运算)

\# Easy

![Solutions video: https://www.youtube.com/watch?v=LPIvL-jvGdA](https://3288217904-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LxJcc9A1TOyn5a5HJQ4%2F-MI7e6tfwpSYuaaVYvxD%2F-MI8M5AvticfZSxJyeJs%2F1601106100379.jpg?alt=media\&token=49943c64-ce01-48b0-b2d6-28878fe0d0c7)

{% tabs %}
{% tab title="Bit vote(wrong)" %}

```python
 class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        res = 0
        for i in range(32):
            ones = 0
            zeros = 0
            x = 1 << i
            for num in nums:
                if num & x != 0:
                    ones += 1
                else:
                    zeros += 1
                if ones > len(nums)//2 or zeros > len(nums)//2:
                    break
            if ones > len(nums)//2:
                res = res | x

        return res
        
# incorrect when test [-2^31], output is [2^31]
# but if coding in C++, then it's correct, why??????                            
```

{% endtab %}

{% tab title="map" %}

```python
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        hashMap = {}
        for num in nums:
            if num not in hashMap:
                hashMap[num] = 1
            else:
                hashMap[num] += 1
        for key, value in hashMap.items():
            if value > len(nums)//2:
                return key
```

{% endtab %}
{% endtabs %}
