Пример #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);
        }