题解 | #设计有setAll功能的哈希表#
设计有setAll功能的哈希表
https://www.nowcoder.com/practice/7c4559f138e74ceb9ba57d76fd169967
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashMap; import java.util.Map; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // 注意 hasNext 和 hasNextLine 的区别 while (in.nextToken() != StreamTokenizer.TT_EOF) { // 注意 while 处理多个 case int n = (int) in.nval; SetAllHashMap map = new SetAllHashMap(); for (int i = 0; i < n; i++) { in.nextToken(); int x = (int) in.nval; if(x == 1) { in.nextToken(); int k = (int) in.nval; in.nextToken(); int v = (int) in.nval; map.set(k, v); } else if(x == 2) { in.nextToken(); out.println(map.get((int)in.nval)); } else if(x == 3){ in.nextToken(); map.setAll((int)in.nval); } } } out.flush(); out.close(); br.close(); } } class SetAllHashMap{ private Map<Integer, Integer[]> map; private Integer setAllVal; private int setAllTime; private int time; public SetAllHashMap() { this.map = new HashMap<>(); time = 0; setAllTime = 0; } //1 public void set(int k, int v){ map.put(k, new Integer[]{v, time++}); } //2 public int get(int k) { if(!map.containsKey(k)) { return -1; } else { return map.get(k)[1] < setAllTime ? setAllVal : map.get(k)[0]; } } //3 public void setAll(int val) { setAllVal = val; setAllTime = time++; } }