设计LRU缓存结构
设计LRU缓存结构
http://www.nowcoder.com/questionTerminal/e3769a5f49894d49b871c09cadd13a61
package main /** * lru design * @param operators int整型二维数组 the ops * @param k int整型 the k * @return int整型一维数组 */ func LRU( operators [][]int , k int ) []int { var list []int var result []int containMap := make(map[int]int) for _,item:= range operators{ if item[0] == 1 { if _ ,ok :=containMap[item[1]];ok { for i,value := range list{ if value == item[1] { list = append(list[:1], list[2:]...) i-- } } } if len(list) >= k { key := list[0] delete(containMap, key) list = list[1:] } containMap[item[1]] = item[2] list = append(list, item[1]) }else if item[0] == 2 { _,ok := containMap[item[1]] if ok { if _ ,ok :=containMap[item[1]];ok { for i,value := range list{ if value == item[1] { list = append(list[:i], list[i+1:]...) i-- } } } list = append(list, item[1]) result = append(result, containMap[item[1]]) }else { result = append(result,-1) } } } return result // write code here }