Skip to content

Commit 2724324

Browse files
author
piotrzientara
committed
improves performance, result 100%
1 parent beee88e commit 2724324

File tree

2 files changed

+26
-28
lines changed

2 files changed

+26
-28
lines changed

equiLeader/equi_leader.rb

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,33 @@
11
class EquiLeader
22
def solution(array)
3-
equi_leaders = []
4-
candidate = find_leader(array)
5-
array.size.times do |index|
6-
if check_candidate(candidate, (array[0..index]))
7-
equi_leaders << index if check_candidate(candidate, array[(index+1)..-1])
8-
end
3+
numbers = Hash.new(0)
4+
max = [0, 0]
5+
leader = ( array.size / 2 )
6+
array.each do |number|
7+
numbers[number] += 1
8+
number_with_count = [number, numbers[number]]
9+
max = number_with_count if number_with_count[1] > max[1]
910
end
10-
equi_leaders.size
11-
end
11+
return 0 if leader >= max[1]
12+
13+
candidate = max[0]
14+
equi_leaders = 0
15+
left_size = 0
16+
right_size = array.size
17+
left_leader_count = 0
18+
right_leader_count = max[1]
1219

13-
def find_leader(array)
14-
size = 0
15-
value = array.first
16-
array.each do |el|
17-
if (size == 0)
18-
size += 1
19-
value = el
20-
else
21-
value != el ? size -= 1 : size += 1
20+
array.each do |number|
21+
left_size += 1
22+
right_size -= 1
23+
if number == candidate
24+
left_leader_count += 1
25+
right_leader_count -= 1
2226
end
27+
is_left_leader = (left_size / 2) < left_leader_count
28+
is_right_leader = (right_size / 2) < right_leader_count
29+
equi_leaders += 1 if is_left_leader && is_right_leader
2330
end
24-
candidate = -1
25-
candidate = value if (size > 0)
26-
leader = -1
27-
leader = candidate if check_candidate(candidate, array)
28-
end
29-
30-
def check_candidate(candidate, array)
31-
count = 0
32-
array.each {|el| count += 1 if (el == candidate) }
33-
count > array.size / 2
31+
equi_leaders
3432
end
3533
end

equiLeader/equi_leader_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
end
88

99
it 'should find equi leader if cut changes the leader' do
10-
# it looks that the equi leader must cannot be more than one number
10+
# it looks that the equi leader cannot be more than one number
1111
array = [1, 2, 2, 1, 1, 1, 1]
1212
expect(subject.solution(array)).to eql(3)
1313
end

0 commit comments

Comments
 (0)