119. Top K Tallest Buildings

Asked in

Top K Tallest Buildings
You are given a list of building heights.

Return the indexes of the top k tallest buildings.

Use 0-based indexing.

If multiple buildings have the same height, the building with the lower index must come first.

Return the selected indexes ordered from tallest building to shortest building.

If two selected buildings have the same height, order them by increasing index.

Method

List<Integer> topKTallestBuildingIndexes(List<Integer> heights, int k)
  • heights is the list of building heights.
  • k is the number of building indexes to return.
  • Return a list containing exactly k indexes.

Constraints

  • 1 ≤ heights.size() ≤ 100,000
  • 0 ≤ heights[i] ≤ 100,000,000
  • 1 ≤ k ≤ heights.size()

Examples

Example 1

Input:
topKTallestBuildingIndexes(heights = List.of(5, 12, 7, 20, 3), k = 2)

Output:
List.of(3, 1)

Explanation:
The tallest building has height 20 at index 3, and the second tallest has height 12 at index 1.

Example 2

Input:
topKTallestBuildingIndexes(heights = List.of(4, 9, 9, 2, 8), k = 3)

Output:
List.of(1, 2, 4)

Explanation:
The two tallest buildings both have height 9 at indexes 1 and 2. Since the heights are the same, the lower index comes first. The next tallest building has height 8 at index 4.

Example 3

Input:
topKTallestBuildingIndexes(heights = List.of(15, 1, 15, 6), k = 4)

Output:
List.of(0, 2, 3, 1)

Explanation:
The buildings at indexes 0 and 2 both have height 15, so index 0 comes first. Then come index 3 with height 6 and index 1 with height 1.




Please use Laptop/Desktop or any other large screen to add/edit code.