-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
61 lines (56 loc) · 1.43 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
using System;
using System.Collections.Generic;
namespace InsertDeleteGetRandomO1
{
class Program
{
static void Main(string[] args)
{
var set = new RandomizedSet();
set.Insert(0);
set.Insert(1);
set.Remove(0);
set.Insert(2);
set.Remove(1);
Console.WriteLine(set.GetRandom());
}
}
public class RandomizedSet
{
private Dictionary<int, int> dict;
private List<int> nums;
private Random random;
public RandomizedSet()
{
dict = new Dictionary<int, int>();
nums = new List<int>();
random = new Random();
}
public bool Insert(int val)
{
if (dict.ContainsKey(val))
return false;
dict.Add(val, nums.Count);
nums.Add(val);
return true;
}
public bool Remove(int val)
{
if (!dict.ContainsKey(val))
return false;
var index = dict[val];
var last = nums[^1];
dict[last] = index;
nums[^1] = val;
nums[index] = last;
nums.RemoveAt(nums.Count - 1);
dict.Remove(val);
return true;
}
public int GetRandom()
{
var index = random.Next(0, nums.Count);
return nums[index];
}
}
}