...
/Solution Review: Finding “K” Largest Elements in the Array
Solution Review: Finding “K” Largest Elements in the Array
Learn how to find “k” largest elements in the array challenge.
We'll cover the following...
Solution: Creating a max-heap and removing max “k” times
Press + to interact
main.cs
MaxHeap.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace chapter_8{class exercise_3{static List<int> findKLargest(int [] arr, int size, int k){MaxHeap<int> heap = new MaxHeap<int>();heap.buildHeap(arr, size);List<int> output = new List<int>();for (int i = 0; (i < k) && (i < size); i++){output.Add(heap.getMax());heap.removeMax();}return output;}static void Main(string[] args){int size = 7;int [] input = { 9, 4, 7, 1, -2, 6, 5 };int [] output = findKLargest(input, size, 4).ToArray();for (int i = 0; i < output.Length; i++){Console.Write(output[i] + " ");}return ;}}}
Here create a heap, and then call the buildHeap
function (lines 14-15) to create a maximum heap from ...