题解 | #设计有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++;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 16:22
主包是26应届生,投大厂简历一直过不了初筛,想问问大家有必要花钱改简历吗
Java抽象带篮子:我之前专门发个帖子说不要付费改简历的,里面还详细写了简历怎么写,你可以去看看
点赞 评论 收藏
分享
VirtualBoo...:都去逗他了?
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务