题解 | #对所有员工的薪水按照salary降序进行1-N的排名#

设计LRU缓存结构

http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61

模拟就行!!!

import java.util.*;


public class Solution {
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
        // write code here
        class Node{
            int key,value;
            Node(int key,int value){
                this.key = key;
                this.value = value;
            }
            // List的indexOf是通过equals比较判断的,这里重写判断key的方法,key相同就代表一样
            public boolean equals(Object obj) {
                Node on = (Node)obj;
                return on.key == this.key;
            }
        }
        // 缓存
        List<Node> list = new ArrayList<>();
        // 题目要的结果集
        List<Integer> res = new ArrayList<>();
        for(int i=0; i<operators.length; i++){
            // set(key,value)
            if(operators[i][0] == 1){
                int index = list.indexOf(new Node(operators[i][1],0));
                // key不存在,就添加到缓存
                if(index == -1){
                    list.add(new Node(operators[i][1],operators[i][2]));
                // 存在就更新value
                }else{
                    Node n = list.get(index);
                    n.value = operators[i][2];
                    list.remove(index);
                    list.add(index,n);
                }
                // 超过k,就把第一个干掉
                if(list.size() == k+1){
                    list.remove(0);
                }
            // get(key)
            }else if(operators[i][0] == 2){
                int index = list.indexOf(new Node(operators[i][1],0));
                // key不存在
                if(index == -1){
                    res.add(-1);
                // key存在,把它移动到缓存的最后
                }else{
                    Node n = list.get(index);
                    res.add(n.value);
                    list.remove(index);
                    list.add(n);
                }
            }
        }
        Object[] rO = res.toArray();
        int[] result = new int[rO.length];
        for(int i=0; i<rO.length; i++){
            result[i] = (int) rO[i];
        }
        return result;
    }
}
全部评论

相关推荐

今天 11:46
Java
如图:也是让我遇到逆天公司了,实习生是按天给工资,不忙直接强制休假了
baskly:公司为北京超图软件股份有限公司武汉分公司,明年公司应该会招新实习生,刷到的小伙伴快跑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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