Skip to content

Instantly share code, notes, and snippets.

@yusufaytas
Created May 15, 2015 09:32
Show Gist options
  • Save yusufaytas/872e0ccc3d2adde478a4 to your computer and use it in GitHub Desktop.
Save yusufaytas/872e0ccc3d2adde478a4 to your computer and use it in GitHub Desktop.
package com.yusufaytas.test.intercom;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
public class TopNNumbers {
private int size;
private String path;
Queue<Integer> queue;
public TopNNumbers(String path, int size) {
if (size < 0) {
throw new IllegalArgumentException("Size must be greater than 0" + size);
}
this.path = path;
this.size = size;
this.queue = new PriorityQueue<Integer>(size);
}
public List<Integer> topN() {
String line = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(this.path));
while ((line = reader.readLine()) != "") {
add(Integer.parseInt(line));
}
reader.close();
} catch (IOException e) {
}
return getNumbers();
}
public void add(int number) {
if (this.queue.size() == size) {
int min = this.queue.peek();
if (number > min) {
this.queue.poll();
this.add(number);
}
} else {
queue.add(number);
}
}
public List<Integer> getNumbers() {
int i = size - 1;
List<Integer> numbers = new ArrayList<Integer>();
int array[] = new int[size];
while (!queue.isEmpty()) {
array[i] = queue.poll();
i--;
}
for (int j = 0; j < array.length; j++) {
numbers.add(array[j]);
}
return numbers;
}
}
@yusufaytas
Copy link
Author

M = Number of Integers
N = Capacity

This algorithm runs log(N)*M

@yusufaytas
Copy link
Author

I've used a heap to decrease complexity of add methods. I don't think we can do better than log(N) here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment