- #1
SlurrerOfSpeech
- 141
- 11
So I came up with the following solution which is n*log2(n) since the input is n elements and I use a binary insertion and calculating the median is constant time. This is passes all the test cases in the tests that don't time out. I need to figure out how to make it faster so I beat the timeouts. I'm pretty much out of ideas.
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Diagnostics.Contracts;
namespace Solution
{
static class Extensions
{
public static void BinaryInsertion(this List<int> list, int val)
{
int index = list.BinarySearch(val);
if(index < 0) index = ~index;
list.Insert(index, val);
}
public static double Median(this List<int> list)
{
Contract.Requires(list.Count > 0, "Method only valid for non-empty lists");
int i = list.Count / 2;
double d = list.Count % 2 == 1 ? (double)list[i] : (double)(list[i-1] + list[i]) / 2.0;
return Math.Round(d, 1);
}
}
class Solution
{
static void Main(string[] args)
{
int n = Int32.Parse(Console.ReadLine());
List<int> list = new List<int>();
for(int i = 0; i < n; ++i)
{
int val = Int32.Parse(Console.ReadLine());
list.InsertInOrder(val);
Console.WriteLine(list.Median());
}
}
}
}