https://leetcode.com/problems/sliding-window-median/
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples: [2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.
For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Therefore, return the median sliding window as [1,-1,-1,3,5,6].
Note: You may assume k is always valid, ie: k is always smaller than input array's size for non-empty array. Answers within 10^-5 of the actual value will be accepted as correct.
Please review for performance. also I am not sure about GetID function is there a smarter way to get the same result of unique number and sorting for median?
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
/// <summary>
/// https://leetcode.com/problems/sliding-window-median/
/// </summary>
[TestClass]
public class SlidingWindowMedianTest
{
[TestMethod]
public void ExampleTest()
{
int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 };
int k = 3;
double[] expected = { 1, -1, -1, 3, 5, 6 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
[TestMethod]
public void ExampleTestFailed()
{
int[] nums = { 1, 4, 2, 3 };
int k = 4;
double[] expected = { 2.5 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
[TestMethod]
public void ExampleTestOverFlow()
{
int[] nums = { 2147483647, 2147483647 };
int k = 2;
double[] expected = { 2147483647.0 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
[TestMethod]
public void ExampleFailed2()
{
int[] nums = { 5, 2, 2, 7, 3, 7, 9, 0, 2, 3 };
int k = 9;
double[] expected = { 3.0, 3.0 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
}
public class SlidingWindowMedian
{
public static double[] MedianSlidingWindow(int[] nums, int k)
{
var res = new List<double>();
var med = new SortedList<long, int>();
for (int i = 0; i < nums.Length; i++)
{
med.Add(GetId(i, nums), nums[i]);
if (med.Count > k)
{
med.Remove(GetId(i - k, nums));
}
if (med.Count == k)
{
if (k % 2 == 0)
{
res.Add( ((long)med[med.Keys[k / 2 - 1]] + med[med.Keys[k / 2]])/2.0 );
}
else
{
res.Add(med[med.Keys[k / 2]]);
}
}
}
return res.ToArray();
}
private static long GetId(int i, int[] nums)
{
return Convert.ToInt64(nums[i]) * nums.Length + i;
}
}
}