-
Notifications
You must be signed in to change notification settings - Fork 292
/
SparseSet.cs
92 lines (73 loc) · 2.18 KB
/
SparseSet.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
88
89
90
91
92
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// A sparse set implementation.
/// </summary>
public class SparseSet : IEnumerable<int>
{
private readonly int[] dense;
private readonly int[] sparse;
public SparseSet(int maxVal, int capacity)
{
sparse = Enumerable.Repeat(-1, maxVal + 1).ToArray();
dense = Enumerable.Repeat(-1, capacity).ToArray();
}
public int Count { get; private set; }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<int> GetEnumerator()
{
return dense.Take(Count).GetEnumerator();
}
/// <summary>
/// Time complexity: O(1).
/// </summary>
public void Add(int value)
{
if (value < 0) throw new Exception("Negative values not supported.");
if (value >= sparse.Length) throw new Exception("Item is greater than max value.");
if (Count >= dense.Length) throw new Exception("Set reached its capacity.");
sparse[value] = Count;
dense[Count] = value;
Count++;
}
/// <summary>
/// Time complexity: O(1).
/// </summary>
public void Remove(int value)
{
if (value < 0) throw new Exception("Negative values not supported.");
if (value >= sparse.Length) throw new Exception("Item is greater than max value.");
if (HasItem(value) == false) throw new Exception("Item do not exist.");
//find element
var index = sparse[value];
sparse[value] = -1;
//replace index with last value of dense
var lastVal = dense[Count - 1];
dense[index] = lastVal;
dense[Count - 1] = -1;
//update sparse for lastVal
sparse[lastVal] = index;
Count--;
}
/// <summary>
/// Time complexity: O(1).
/// </summary>
public bool HasItem(int value)
{
var index = sparse[value];
return index != -1 && dense[index] == value;
}
/// <summary>
/// Time complexity: O(1).
/// </summary>
public void Clear()
{
Count = 0;
}
}