mirror of
https://github.com/Rainyy21/framework_note.git
synced 2026-10-11 00:30:29 -04:00
vault backup: 2026-05-30 16:02:33
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
---
|
||||
id: 169
|
||||
title: Majority Element
|
||||
difficulty: Easy
|
||||
tags:
|
||||
- array
|
||||
- hash-table
|
||||
- sorting
|
||||
- counting
|
||||
status: Solved
|
||||
date_solved: 2026-05-26
|
||||
leetcode_url: https://leetcode.com/problems/majority-element/
|
||||
review_needed: false
|
||||
---
|
||||
|
||||
# 169. Majority Element
|
||||
|
||||
> [!info] **Problem Link**: [LeetCode - Majority Element](https://leetcode.com/problems/majority-element/)
|
||||
|
||||
## 📝 Problem Description
|
||||
|
||||
Given an array `nums` of size `n`, return the majority element.
|
||||
|
||||
The majority element is the element that appears more than `[n / 2]` times. You may assume that the majority element always exists in the array.
|
||||
|
||||
|
||||
---
|
||||
|
||||
### 📥 Example 1
|
||||
> **Input:** `nums = [3,2,3]`
|
||||
> **Output:** `3`
|
||||
|
||||
### 📥 Example 2
|
||||
> **Input:** `nums = [2,2,1,1,1,2,2]`
|
||||
> **Output:** `2`
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 💡 Approaches & Explanations
|
||||
have cont, if cont is equal to 0 the res become the highest amount
|
||||
if i equal to the res than add one to count anything else cont -1
|
||||
return res at the end
|
||||
|
||||
## 💻 Code Implementations
|
||||
|
||||
### Python3
|
||||
```python
|
||||
class Solution:
|
||||
def majorityElement(self, nums: List[int]) -> int:
|
||||
cont = 0
|
||||
res = None
|
||||
for i in nums:
|
||||
if cont == 0:
|
||||
res = i
|
||||
cont +=1 if res == i else -1
|
||||
return res
|
||||
```
|
||||
Reference in New Issue
Block a user