Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8d95f2b

Browse files
committed
day-7
1 parent 373a19b commit 8d95f2b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎majority-element.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def majorityElement(self, nums: List[int]) -> int:
3+
length = len(nums)//2
4+
# Time limit will exceed in case of long arrays [5k elements]
5+
# majority = 0
6+
# element = 0
7+
8+
# for i in nums:
9+
# numCount = nums.count(i)
10+
# if numCount > length and numCount > majority:
11+
# majority = numCount
12+
# element = i
13+
# return element
14+
15+
# Best solution
16+
# nums.sort()
17+
# element = nums[length]
18+
# return element
19+
20+
# if not nums:
21+
# return None
22+
23+
# Boyce-Moore algorithm
24+
count = 0
25+
candidate = None
26+
27+
for num in nums:
28+
if count == 0:
29+
candidate = num
30+
count += (1 if num == candidate else -1)
31+
32+
return candidate

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /