-
-
Save VegaFromLyra/42879587e031c6cab3e7 to your computer and use it in GitHub Desktop.
Max N numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
// Given an array of numbers and a value 'k', find k max numbers from this array | |
// Time: (n - k) * klogk | |
// Space: O(1) - Not including the array we allocate for the output | |
namespace MaxNNumbers | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) { | |
int[] arr= {11, 3, 1, 5, 7, 9, 8, 20}; | |
int k = 4; | |
var result = maxN(arr, k); | |
Console.WriteLine("The max {0} numbers are", k); | |
foreach (var item in result) | |
{ | |
Console.Write(item + " "); | |
} | |
Console.WriteLine(" "); | |
} | |
static int[] maxN(int[] arr, int k) { | |
int[] minHeap = new int[k]; | |
int counter = 0; | |
for(int i = 0; i < arr.Length; i++) { | |
if (counter < k - 1) { | |
minHeap[counter++] = arr[i]; | |
} else if (counter == k - 1) { | |
minHeap[counter++] = arr[i]; | |
buildMinHeap(minHeap, k); | |
} else if (arr[i] > minHeap[0]) { | |
minHeap[0] = arr[i]; | |
buildMinHeap(minHeap, k); | |
} | |
} | |
return minHeap; | |
} | |
static void buildMinHeap(int[] arr, int length) { | |
for(int i = (length - 1)/2; i >= 0; i--) { | |
minHeapify(arr, i, length); | |
} | |
} | |
static void minHeapify(int[] arr, int index, int length) { | |
int left = (2 * index) + 1; | |
int right = (2 * index) + 2; | |
int smallest = index; | |
if ((left < length) && (arr[left] < arr[smallest])) { | |
smallest = left; | |
} | |
if ((right < length) && (arr[right] < arr[smallest])) { | |
smallest = right; | |
} | |
if (index != smallest) { | |
int temp = arr[index]; | |
arr[index] = arr[smallest]; | |
arr[smallest] = temp; | |
minHeapify(arr, smallest, length); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment