You are viewing a single comment's thread. Return to all comments →
For those that write the challenge in C#, there is no built-in .NET collection that: only stores keys, keeps them sorted, and allows duplicates.
The only way that I have managed to do it is implement my custom data structure.
static void Median(string[] a, int[] x) { SortedBag<int> numberList = new SortedBag<int>(); for (int i = 0; i < a.Length; i++) { var operation = a[i]; //"a" or "r" var operationNumber = x[i]; // integer if (operation == "r") { if (!numberList.Contains(operationNumber)) { Console.WriteLine("Wrong!"); continue; } else { if (numberList.Contains(operationNumber)) numberList.Remove(operationNumber); } } else { numberList.Add(operationNumber); } if (numberList.Count == 0) { Console.WriteLine("Wrong!"); } else if (numberList.Count % 2 == 0) { var indexToCalculate = (numberList.Count) / 2; decimal median = (decimal)(numberList[indexToCalculate - 1] + (decimal)numberList[indexToCalculate]) / 2; Console.WriteLine(median); } else { int indexToCalculate = 0; if (numberList.Count != 1) { indexToCalculate = (numberList.Count) / 2; } var median = numberList[indexToCalculate]; Console.WriteLine(median); } } } public class SortedBag<T> where T : IComparable<T> { private readonly List<T> _items = new(); public void Add(T item) { int index = _items.BinarySearch(item); if (index < 0) index = ~index; _items.Insert(index, item); } public bool Remove(T item) { int index = _items.BinarySearch(item); if (index < 0) return false; while (index > 0 && _items[index - 1].CompareTo(item) == 0) index--; _items.RemoveAt(index); return true; } public int Count => _items.Count; // Indexer support public T this[int index] => _items[index]; public bool Contains(T item) { return _items.BinarySearch(item) >= 0; } }
Seems like cookies are disabled on this browser, please enable them to open this website
Median Updates
You are viewing a single comment's thread. Return to all comments →
For those that write the challenge in C#, there is no built-in .NET collection that: only stores keys, keeps them sorted, and allows duplicates.
The only way that I have managed to do it is implement my custom data structure.