-
Notifications
You must be signed in to change notification settings - Fork 115
/
0715-RangeModule.cs
87 lines (72 loc) · 2.45 KB
/
0715-RangeModule.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//-----------------------------------------------------------------------------
// Runtime: 488ms
// Memory Usage: 52 MB
// Link: https://leetcode.com/submissions/detail/383925072/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _0715_RangeModule
{
private readonly SortedList<int, int> list;
public _0715_RangeModule()
{
list = new SortedList<int, int>();
}
public void AddRange(int left, int right)
{
var leftIndex = GetIndex(left);
if (leftIndex >= 0) left = list.Keys[leftIndex];
else leftIndex = ~leftIndex;
var rightIndex = GetIndex(right);
if (rightIndex >= 0) right = list.Values[rightIndex];
else rightIndex = ~rightIndex - 1;
for (int i = leftIndex; i <= rightIndex; i++)
list.RemoveAt(leftIndex);
list[left] = right;
}
public bool QueryRange(int left, int right)
{
var leftIndex = GetIndex(left);
var rightIndex = GetIndex(right);
return leftIndex == rightIndex && leftIndex >= 0;
}
public void RemoveRange(int left, int right)
{
var leftIndex = GetIndex(left);
var rightIndex = GetIndex(right);
if (rightIndex >= 0)
list[right] = list.Values[rightIndex];
else
rightIndex = ~rightIndex - 1;
if (leftIndex >= 0)
{
list[list.Keys[leftIndex]] = left;
leftIndex++;
}
else
leftIndex = ~leftIndex;
for (int i = leftIndex; i <= rightIndex; i++)
list.RemoveAt(leftIndex);
}
private int GetIndex(int value)
{
var index = Array.BinarySearch(list.Keys.ToArray(), value);
if (index >= 0) return index;
index = ~index;
if (index > 0 && list.Values[index - 1] >= value)
return index - 1;
else
return ~index;
}
}
/**
* Your RangeModule object will be instantiated and called as such:
* RangeModule obj = new RangeModule();
* obj.AddRange(left,right);
* bool param_2 = obj.QueryRange(left,right);
* obj.RemoveRange(left,right);
*/
}