SAYAN-2000
/
Must-Do-Coding-Questions-For-Service-Based-Companies-and-Product-Based-Companies.
Public
forked from rohitjila/Must-Do-Coding-Questions-For-Service-Based-Companies-and-Product-Based-Companies.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMajority Element
43 lines (38 loc) · 1.08 KB
/
Majority Element
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
43
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
num1,num2=self.majority(nums)
count1,count2 = 0,0
n=len(nums)
ans=[]
for i in range(n):
if (nums[i] == num1):
count1+=1
elif (nums[i] == num2):
count2+=1
print(count1,count2)
if (count1 > n//3):
ans.append(num1)
if (count2 > n//3):
ans.append(num2)
return ans
def majority(self,nums):
n=len(nums)
count1=0
count2=0
num1=-1
num2=-1
for i in range(n):
if (nums[i] == num1):
count1+=1
elif (nums[i] == num2):
count2+=1
elif (count1 == 0):
num1=nums[i]
count1=1
elif (count2 == 0):
num2=nums[i]
count2=1
else:
count1-=1
count2-=1
return (num1,num2)