-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
70 lines (67 loc) · 1.95 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
namespace OnlineElection
{
class Program
{
static void Main(string[] args)
{
int[] person = {0, 1, 2, 2, 1};
int[] times = {20, 28, 29, 54, 56};
var t = new TopVotedCandidate(person, times);
Console.WriteLine(t.Q(55));
}
}
public class TopVotedCandidate
{
private readonly int[] _persons;
private readonly int[] _times;
private readonly Dictionary<int, int> winner;
public TopVotedCandidate(int[] persons, int[] times)
{
_persons = persons;
_times = times;
winner = new Dictionary<int, int>();
var votes = new Dictionary<int, int>();
for (int i = 0; i < times.Length; i++)
{
if (!votes.ContainsKey(persons[i]))
votes[persons[i]] = 1;
else
votes[persons[i]]++;
var max = votes.Max(v => v.Value);
for (int j = i; j >= 0; j--)
{
if (votes[persons[j]] == max)
{
this.winner[times[i]] = persons[j];
break;
}
}
}
}
public int Q(int t)
{
int li = 0, hi = _times.Length - 1, index = -1;
while (li < hi)
{
int mid = li + (hi - li) / 2;
if (t == _times[mid])
{
index = mid;
break;
}
if (_times[mid] > t)
hi = mid;
else
li = mid + 1;
}
var mark = index == -1 ? li : index;
if (t < _times[mark])
mark--;
return winner[_times[mark]];
}
}
}