-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajority_elementDay4.py
More file actions
42 lines (35 loc) · 1003 Bytes
/
Copy pathMajority_elementDay4.py
File metadata and controls
42 lines (35 loc) · 1003 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#Brute Force Solution
# class Solution:
# def majorityElement(self, nums: List[int]) -> int:
# n = len(nums)
#
# for i in range(n):
# count = 0
# for j in range(n):
# if nums[j] == nums[i]:
# count = count +1
# if count > n//2:
# return nums[i]
#Better Solution
# class Solution:
# def majorityElement(self, nums: List[int]) -> int:
# count_map = {}
# n = len(nums)
#
# for num in nums:
# count_map[num] = count_map.get(num, 0) + 1
# if count_map[num] > n // 2:
# return num
#Optimal Solution
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
if num == candidate:
count += 1
else:
count -= 1
return candidate