-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN3_elements.py
45 lines (40 loc) · 1.13 KB
/
N3_elements.py
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
44
45
'''
A -> read only array of n integers
check if any ele occurs more than n/3 times|TC - O(N),linear time|SC - O(1),constant additional space
Max > n/3 elements -> 2
'''
class Solution:
# @param A : tuple of integers
# @return an integer
def repeatedNumber(self, A):
ele1 = 1 #random number
ele2 = 2 #random number
freq1 = 0
freq2 = 0
for i in A:
if i == ele1:
freq1 += 1
elif i == ele2:
freq2 += 1
elif freq1 == 0:
ele1 = i
freq1 = 1
elif freq2 == 0:
ele2 = i
freq2 = 1
# Current ele does not match to any of these two eles so reduce both
else:
freq1 -= 1
freq2 -= 1
freq1 = freq2 = 0
for i in A:
if i == ele1:
freq1 += 1
elif i == ele2:
freq2 += 1
if freq1 > len(A)/3:
return ele1
elif freq2 > len(A)/3:
return ele2
else:
return -1