Skip to content

Instantly share code, notes, and snippets.

@Ilchert
Last active March 19, 2024 11:25
Show Gist options
  • Save Ilchert/afe5334acfde41347529f75f779cab98 to your computer and use it in GitHub Desktop.
Save Ilchert/afe5334acfde41347529f75f779cab98 to your computer and use it in GitHub Desktop.
public class Container
{
private SortedDictionary<int, int> _storage = new();
private int _count = 0;
public Container()
{
// write your code here
}
public void Add(int value)
{
_count++;
_storage.TryGetValue(value, out var count);
_storage[value] = count + 1;
}
public bool Delete(int value)
{
if (!_storage.TryGetValue(value, out var count))
return false;
_count--;
if (count == 1)
return _storage.Remove(value);
_storage[value] = count - 1;
return true;
}
public int GetMedian()
{
if (_count == 0)
throw new InvalidOperationException();
int index;
if (_count % 2 == 0)
index = _count / 2;
else
index = _count / 2 + 1;
foreach (var (k, v) in _storage)
{
if (index <= v)
return k;
index -= v;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment