Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Есть последовательность событий, каждое событие это пара user_id, time, события отсортированы по времени.
- // Нужно уметь отвечать на вопрос, сколько за последние 5 минут было пользователей, которые задали >= 1000 запросов.
- //
- // class RobotStatistics {
- // void OnEvent(time_t now, int userId);
- // int GetRobotCount(time_t now);
- // };
- // новое решение: https://pastebin.com/BxRjsSVf
- class RobotStatistics
- {
- private List<(DateTime time, int userId)> _requests = new List<(DateTime time, int userId)>();
- private Dictionary<int, int> _countByUser = new Dictionary<int, int>();
- private int _robotCount;
- public void OnEvent(DateTime time, int userId)
- {
- _requests.Add((time, userId));
- if (!countByUser.Contains(userId))
- {
- countByUser[userId] = 0;
- }
- countByUser[userId]++;
- if (_countByUser[_requests[i].userId] == 1000)
- {
- _robotCount++;
- }
- ClearOldRequests(DateTime time);
- }
- private void ClearOldRequests(DateTime time)
- {
- var startTime = time.AddMinute(-5);
- for(var i = 0; i < _requests.Length && _requests[i].time < startTime; i++)
- {
- if (_countByUser[_requests[i].userId] == 1000)
- {
- _robotCount--;
- }
- _countByUser[_requests[i].userId]--;
- }
- // тут ещё надо удалить как-то неактуальные запросы, возможно переделать List<> в LinkedList<>
- }
- public int GetRobotCount(DateTime time)
- {
- ClearOldRequests(time);
- return _robotCount;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement