コード例 #1
0
        public IList <int[]> GetSkyline(int[,] buildings)
        {
            List <int[]> result = new List <int[]>();

            if (buildings == null || buildings.GetLength(0) == 0 || buildings.GetLength(1) == 0)
            {
                return(result);
            }
            SkyLinePoint[] points = new SkyLinePoint[buildings.GetLength(0) * 2];
            // Convert building left edge, right edge and height into points.
            int index = 0;

            for (var i = 0; i < buildings.GetLength(0); i++)
            {
                var x  = buildings[i, 0];
                var x2 = buildings[i, 1];
                var y  = buildings[i, 2];
                points[index++] = new SkyLinePoint(x, y, true);
                points[index++] = new SkyLinePoint(x2, y, false);
            }

            Array.Sort(points);

            MaxHeap <int> heap = new MaxHeap <int>();

            heap.Push(0);
            int prevMax = 0;

            foreach (var point in points)
            {
                if (point.IsStart)
                {
                    heap.Push(point.Y);

                    int curMaxVal = heap.Peek();
                    if (curMaxVal > prevMax)
                    {
                        result.Add(new[] { point.X, point.Y });
                        prevMax = curMaxVal;
                    }
                }
                else
                {
                    heap.Remove(point.Y);
                    int curMaxVal = heap.Peek();
                    if (curMaxVal < prevMax)
                    {
                        result.Add(new[] { point.X, curMaxVal });
                        prevMax = curMaxVal;
                    }
                }
            }

            return(result);
        }
コード例 #2
0
ファイル: MinMaxHeap.cs プロジェクト: viktordd/HackerRank
        public void MaxHeap_Solutions()
        {
            var maxHeap = new MaxHeap <int>();

            maxHeap.Push(6);
            Assert.AreEqual(6, maxHeap.Peek());

            maxHeap.Push(5);
            Assert.AreEqual(6, maxHeap.Peek());

            maxHeap.Push(4);
            Assert.AreEqual(6, maxHeap.Peek());

            maxHeap.Push(3);
            Assert.AreEqual(6, maxHeap.Peek());

            maxHeap.Push(2);
            Assert.AreEqual(6, maxHeap.Peek());

            Assert.AreEqual(6, maxHeap.PopPush(1));

            Assert.AreEqual(5, maxHeap.Peek());

            maxHeap.Push(7);
            Assert.AreEqual(7, maxHeap.Peek());

            Assert.AreEqual(7, maxHeap.Pop());
            Assert.AreEqual(5, maxHeap.Pop());
            Assert.AreEqual(4, maxHeap.Pop());
            Assert.AreEqual(3, maxHeap.Pop());
            Assert.AreEqual(2, maxHeap.Pop());
            Assert.AreEqual(1, maxHeap.Pop());

            Assert.AreEqual(0, maxHeap.Count);
        }