-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathappear_more_than_n_github.py
More file actions
74 lines (57 loc) · 1.88 KB
/
appear_more_than_n_github.py
File metadata and controls
74 lines (57 loc) · 1.88 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Candidate:
def __init__(self):
self.value = None
self.count = 0
class MoreThanNDKFinder:
def __init__(self, numbers, k):
self.numbers = numbers
self.k = k
self.n = len(numbers)
def find_elements(self):
if self.k < 2:
return []
# Step 1: Create k-1 candidates
candidates = [Candidate() for _ in range(self.k - 1)]
# Step 2: Moore’s Voting (candidate selection)
for num in self.numbers:
found = False
# Case 1: number already a candidate
for c in candidates:
if c.value == num:
c.count += 1
found = True
break
if found:
continue
# Case 2: empty slot exists
for c in candidates:
if c.count == 0:
c.value = num
c.count = 1
found = True
break
# Case 3: no slot → decrement all
if not found:
for c in candidates:
c.count -= 1
# Step 3: Verify actual counts
result = []
for c in candidates:
if c.value is not None:
actual = self.numbers.count(c.value)
if actual > self.n // self.k:
result.append((c.value, actual))
return result
def main():
numbers = [3, 4, 2, 2, 1, 2, 3, 3]
k = 4
finder = MoreThanNDKFinder(numbers, k)
result = finder.find_elements()
print("Array:", numbers)
if not result:
print("No elements appear more than n/k times.")
else:
for value, count in result:
print(f"Number: {value} → Count: {count}")
if __name__ == "__main__":
main()