Skip to content

Commit 7158253

Browse files
committed
task3 solution
1 parent 979d612 commit 7158253

File tree

1 file changed

+52
-17
lines changed

1 file changed

+52
-17
lines changed
Lines changed: 52 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,60 @@
1+
class Array
2+
def swap(i, j)
3+
return if i == j
4+
self[i], self[j] = self[j], self[i]
5+
end
6+
end
17

8+
### Decimal dominants
9+
# Given an array with `n` keys, design an algorithm to find all values that occur more than `n/10` times. The expected running time of your algorithm should be linear.
210

11+
n = 1000
312

13+
a = (n / 2).times.map { rand(0..4) } + (n / 2).times.map { rand(0..99) }
14+
d = 10
415

16+
expected = a.tally.select { |_, v| v > n / d }.keys
517

18+
### Solution
619

7-
----------------------------------
20+
def count_dominants(arr, lo, hi, d, result)
21+
return if lo >= hi
822

9-
Hint: determine the
10-
(
11-
12-
/
13-
10
14-
)
15-
16-
17-
(n/10)
18-
th
19-
largest key using quickselect and check if it occurs more than
20-
21-
/
22-
10
23-
n/10 times.
23+
i = lo
24+
lt = lo
25+
rt = hi
26+
pivot = arr[lo]
2427

25-
Alternate solution hint: use 9 counters.
28+
while i <= rt
29+
case arr[i] <=> pivot
30+
when -1
31+
arr.swap(i, lt)
32+
i += 1
33+
lt += 1
34+
when 1
35+
arr.swap(i, rt)
36+
rt -= 1
37+
else
38+
i += 1
39+
end
40+
end
41+
42+
count = i - lt
43+
44+
result << arr[lt] if count > arr.size / d
45+
46+
count_dominants(arr, lo, lt - 1, d, result)
47+
count_dominants(arr, rt + 1, hi, d, result)
48+
end
49+
50+
result = []
51+
count_dominants(a, 0, a.size - 1, d, result)
52+
53+
p expected.sort!
54+
p result.sort!
55+
p expected == result
56+
57+
58+
# Hint: determine the `(n/10)^th` largest key using quickselect and check if it occurs more than `n/10` times.
59+
60+
# Alternate solution hint: use 9 counters.

0 commit comments

Comments
 (0)