Created
July 15, 2017 08:37
-
-
Save rishiloyola/316394429f5c35a9934757c084daf8ec to your computer and use it in GitHub Desktop.
This file contains 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
package test; | |
import java.io.BufferedReader; | |
import java.io.FileReader; | |
import java.util.PriorityQueue; | |
public class TopN { | |
public static void GetNum(String fileName, int N) { | |
PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(N); | |
BufferedReader bufferedReader = null; | |
try { | |
bufferedReader = new BufferedReader(new FileReader(fileName)); | |
String line = bufferedReader.readLine(); | |
while (line != null) { | |
try { | |
int number = Integer.valueOf(line); | |
if (priorityQueue.size() < N) { | |
priorityQueue.add(number); | |
} else { | |
int head = priorityQueue.element(); | |
if (number > head) { | |
priorityQueue.add(number); | |
priorityQueue.remove(); | |
} | |
} | |
} catch (NumberFormatException e) { | |
System.out.println("Error"); | |
} | |
line = bufferedReader.readLine(); | |
} | |
System.out.println(priorityQueue.toString()); | |
} catch(Exception ex) { | |
System.out.println("Error"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment