题解 | #设计有setAll功能的哈希表#
设计有setAll功能的哈希表
https://www.nowcoder.com/practice/7c4559f138e74ceb9ba57d76fd169967
import java.io.*; import java.util.HashMap; public class Main { public static HashMap<Integer, int[]> map = new HashMap<>(); public static int cnt, setAllValue, setAllTime = -1, n; public static int[][] op = new int[100001][3]; public static void main(String[] args) throws IOException { n = sc.nextInt(); for (int i = 0; i < n; i++) { op[i][0] = sc.nextInt(); // 读取操作类型 op[i][1] = sc.nextInt(); // 读取第一个参数 // 只有操作类型为1时,才会有第三个参数 if (op[i][0] == 1) { op[i][2] = sc.nextInt(); // 读取第二个参数 } } for (int i = 0; i < n; i++) { if (op[i][0] == 1) { map.put(op[i][1], new int[]{op[i][2], cnt++}); } else if (op[i][0] == 2) { if (map.containsKey(op[i][1])){ int[] tmp = map.get(op[i][1]); if (tmp[1] > setAllTime) { sc.pw.write(tmp[0]+ "\n"); } else { sc.pw.write(setAllValue + "\n"); } } else { sc.pw.write(-1 + "\n"); } } else { setAllValue = op[i][1]; setAllTime = cnt++; } } sc.pw.flush(); } public static class sc { static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); public static int nextInt() throws IOException { st.nextToken(); return (int) st.nval; } public static <T> void write(T o) { pw.print(o); } } }
setAll功能的哈希表
其实是在常规hashmap上扩展的,在value部分加了点东西
先来三个全局变量:
cnt:插入时序
setAllValue:格式化目标值
setAllTime:格式化时序
1. put(int k, v)
存k-v时,v除了一般的v,还得存当前cnt
2. get(int k)
返回k对应的v,不存在则返回-1,注意v的结构不再是单独的v,而是一个小数组
而且,如果该k的时序在setAllTime之后,其实应该返回setAllValue
3. setAll(int v)
setAllValue = 该是多少就是多少
setAllTime = cnt ++;