-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPart2.java
More file actions
83 lines (79 loc) · 2.4 KB
/
Copy pathPart2.java
File metadata and controls
83 lines (79 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.SortedSet;
import java.util.TreeSet;
public class Part2 {
/**
* @param x the number of lines to read in
* @param r the reader to read from
* @param w the writer to write to
* @throws IOException
*/
public static void doIt(int x, BufferedReader r, PrintWriter w)
throws IOException {
LinkedList<String> words = new LinkedList<>();
SortedSet<String> sortedWords = new TreeSet<>();
String line = r.readLine();
while(line != null){
if(x == 1 || x == 0){
w.println(line);
}
else if(words.size() < x-1){
words.add(line);
sortedWords.add(line);
}
else if(words.size() == x-1){
words.add(line);
sortedWords.add(line);
if(sortedWords.last().equals(line)){
w.println(line);
}
sortedWords.remove(words.getFirst());
words.removeFirst();
}
line = r.readLine();
}
}
/**
* The driver. Open a BufferedReader and a PrintWriter, either from System.in
* and System.out or from filenames specified on the command line, then call doIt.
* @param args
*/
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
int x;
if (args.length == 0) {
x = 3;
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if( args.length == 1) {
x = Integer.parseInt(args[0]);
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 2) {
x = Integer.parseInt(args[0]);
r = new BufferedReader(new FileReader(args[1]));
w = new PrintWriter(System.out);
} else {
x = Integer.parseInt(args[0]);
r = new BufferedReader(new FileReader(args[1]));
w = new PrintWriter(new FileWriter(args[2]));
}
long start = System.nanoTime();
doIt(x, r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 1e-9 * (stop-start));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
}