题意
数据流读入数字(保证>=1),i最初=0,当i+1出现时,输出i+1及其后连续的输入过的数字,否则什么也不输出。
例子:
输入:1 输出:1
输入:3 输出:
输入:4 输出:
输入:6 输出:
输入:2 输出:2 3 4
题解
用链表+headMap+tailMap存。
总时间复杂度O(n).
代码
import java.util.HashMap;
import java.util.Scanner;
class Node{
int val;
Node next;
public Node(int val) {
this.val=val;
}
}
class Message{
HashMap<Integer,Node> headMap=new HashMap();
HashMap<Integer,Node> tailMap=new HashMap();
int lastPrint=0;
public void receive(int num) {
Node node=new Node(num);
headMap.put(num, node);
tailMap.put(num,node);
if(headMap.containsKey(num+1)) {
node.next=headMap.get(num+1);
headMap.remove(num+1);
headMap.put(num,node);
}
if(tailMap.containsKey(num-1)) {
tailMap.get(num-1).next=node;
tailMap.remove(num-1);
tailMap.put(num,node);
}
if(headMap.containsKey(lastPrint+1)) {
print();
}
}
private void print() {//
Node node=headMap.get(lastPrint+1);
headMap.remove(lastPrint+1);
while(node.next!=null) {
System.out.println(node.val);
++lastPrint;
node=node.next;
}
System.out.println(node.val);
++lastPrint;
tailMap.remove(node.val);
}
}
public class Main {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
Message mes=new Message();
while(in.hasNext()) {
int num=in.nextInt();
mes.receive(num);
}
}
}