// 如果key存在于缓存中,则返回关键字的值,否则返回-1 func(this *LRUCache) Get(key int) int { if ele, ok := this.keysMap[key]; ok { this.updateListKey(key) return ele } return-1 }
func(this *LRUCache) Put(key int, value int) { // 关键字存在 则更新值为value // 不存在,则插入value // 如果插入超过数量capacity 则删除最久没有使用的关键字【list] if _, ok := this.keysMap[key]; ok { this.updateListKey(key) this.keysMap[key] = value } else { this.updateListKey(key) this.keysMap[key] = value iflen(this.keysList) > this.capacity { delete(this.keysMap, this.keysList[0]) // 这里删除key 从list队列中获取 this.keysList = this.keysList[1:] } } }
func(this *LRUCache) updateListKey(key int) { for i := 0; i < len(this.keysList); i++ { if key == this.keysList[i] { this.keysList = append(this.keysList[:i], this.keysList[i+1:]...) // 删除该key, 然后放在末尾 break } } this.keysList = append(this.keysList, key) }
// Insert 将word插入到trie中 func(this *Trie) Insert(word string) { node := this.root for _, ch := range word { index := ch - 'a' if node.children[index] == nil { node.children[index] = &TrieNode{} } node = node.children[index] } node.isEnd = true// 标记单词结束的节点 }
// Search 在trie中搜索word func(this *Trie) Search(word string) bool { node := this.root for _, ch := range word { index := ch - 'a' if node.children[index] == nil { returnfalse// 如果路径中的节点不存在,说明word不在trie中 } node = node.children[index] } return node.isEnd // 检查最后一个节点是否标记为单词结尾 }
// StartsWith 返回trie中是否有任何单词以prefix为前缀 func(this *Trie) StartsWith(prefix string) bool { node := this.root for _, ch := range prefix { index := ch - 'a' if node.children[index] == nil { returnfalse// 如果路径中的节点不存在,说明没有以prefix为前缀的word } node = node.children[index] } returntrue// 所有的char都在路径中,说明trie有以prefix为前缀的word }
/** * Your Trie object will be instantiated and called as such: * obj := Constructor(); * obj.Insert(word); * param_2 := obj.Search(word); * param_3 := obj.StartsWith(prefix); */
func(this *WordDictionary) Search(word string) bool { if _, ok := this.wordMap[word]; ok {
returntrue } elseif strings.Contains(word, ".") { for key, _ := range this.wordMap { iflen(key) == len(word) { flag := true for i := 0; i < len(word); i++ { if key[i] == word[i] || word[i] == '.' {
} else { flag = false } } if flag == true { returntrue } } } returnfalse } returnfalse }
/** * Your WordDictionary object will be instantiated and called as such: * obj := Constructor(); * obj.AddWord(word); * param_2 := obj.Search(word); */
/* Below is the interface for Iterator, which is already defined for you. * * type Iterator struct { * * } * * func (this *Iterator) hasNext() bool { * // Returns true if the iteration has more elements. * } * * func (this *Iterator) next() int { * // Returns the next element in the iteration. * } */
type PeekingIterator struct { iter *Iterator _hasNext bool _next int }
// Encodes a URL to a shortened URL. func(this *Codec) encode(longUrl string) string { this.nums++ this.dataId[this.nums] = longUrl res := "http://tinyurl.com/" + strconv.Itoa(this.nums) return res }
// Decodes a shortened URL to its original URL. func(this *Codec) decode(shortUrl string) string { index := strings.Split(shortUrl, "/") tmp := index[len(index)-1] idx, _ := strconv.Atoi(tmp) long := this.dataId[idx] return long }
/** * Your Codec object will be instantiated and called as such: * obj := Constructor(); * url := obj.encode(longUrl); * ans := obj.decode(url); */
func(this *MyLinkedList) Get(index int) int { if index < 0 || index >= this.Size { return-1 } //dummyHead := &ListNode{0, this.head} cur := this.dummyHead.Next for index != 0 && cur != nil { cur = cur.Next index-- } return cur.Val }
func(this *MyLinkedList) AddAtIndex(index int, val int) { if index >= 0 && index <= this.Size { cur := this.dummyHead //cur 等于虚拟头节点,插入节点的前驱 for i := 0; i < index; i++ { cur = cur.Next } newNode := &ListNode{val, cur.Next} cur.Next = newNode this.Size++ } if index < 0 { this.AddAtIndex(0, val) this.Size++ } if index > this.Size { return// 这个return 到哪里了? 代表结束这个程序吗? } }
if index >= 0 && index < this.Size { cur := this.dummyHead //cur 等于虚拟头节点,插入节点的前驱 for i := 0; i < index; i++ { cur = cur.Next } cur.Next = cur.Next.Next this.Size-- } return }
/** * Your MyLinkedList object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Get(index); * obj.AddAtHead(val); * obj.AddAtTail(val); * obj.AddAtIndex(index,val); * obj.DeleteAtIndex(index); */
funcaverage(s []int)float64 { sum := 0 for _,v := range s { sum +=v } returnfloat64(sum)/float64(len(s)) }
/** * Your UndergroundSystem object will be instantiated and called as such: * obj := Constructor(); * obj.CheckIn(id,stationName,t); * obj.CheckOut(id,stationName,t); * param_3 := obj.GetAverageTime(startStation,endStation); */
func(this *SubrectangleQueries) GetValue(row int, col int) int { return this.rectangle[row][col] }
/** * Your SubrectangleQueries object will be instantiated and called as such: * obj := Constructor(rectangle); * obj.UpdateSubrectangle(row1,col1,row2,col2,newValue); * param_2 := obj.GetValue(row,col); */
type LockingTree struct { parent []int lockNodeUser []int children [][]int }
funcConstructor(parent []int) LockingTree { n := len(parent) lockNodeUser := make([]int, n) children := make([][]int, n) for i := 0; i < n; i++ { lockNodeUser[i] = -1 p := parent[i] if p != -1 { children[p] = append(children[p], i) } } return LockingTree{parent, lockNodeUser, children} }
func(this *LockingTree) Lock(num int, user int) bool { if this.lockNodeUser[num] == -1 { this.lockNodeUser[num] = user returntrue } returnfalse }
func(this *LockingTree) Unlock(num int, user int) bool { if this.lockNodeUser[num] == user { this.lockNodeUser[num] = -1 returntrue } returnfalse }
func(this *LockingTree) Upgrade(num int, user int) bool { res := this.lockNodeUser[num] == -1 && !this.hasLockedAncestor(num) && this.checkAndUnlockDescendant(num) if res { this.lockNodeUser[num] = user } return res }
func(this *LockingTree) hasLockedAncestor(num int) bool { num = this.parent[num] for num != -1 { if this.lockNodeUser[num] != -1 { returntrue } num = this.parent[num] } returnfalse }
func(this *LockingTree) checkAndUnlockDescendant(num int) bool { res := false if this.lockNodeUser[num] != -1 { res = true } this.lockNodeUser[num] = -1 for _, child := range this.children[num] { if this.checkAndUnlockDescendant(child) { res = true } } return res }
func(this *ATM) Deposit(banknotesCount []int) { for i , count := range banknotesCount{ this.orderList[i] += count
}
}
func(this *ATM) Withdraw(amount int) []int { //使用整除法 ans := make([]int, 5) for i := 4; i >= 0; i-- { ans[i] = min(amount/price[i],this.orderList[i]) amount -= ans[i]*price[i] } if amount > 0 { return []int{-1} } for idx,v := range ans { this.orderList[idx] -= v } return ans // 注意试着返回是需要钞票的数量,不是钞票的剩余数量 }
funcmin(a, b int)int { if a > b { return b } return a }
func(h *FoodHeap) Push(f interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, // not just its contents. food := f.(*Food) food.Idx = h.Len() *h = append(*h, food) }
func(h *FoodHeap) Pop() interface{} { a := *h; v := a[len(a) - 1]; *h = a[:len(a) - 1]; return v }
// 以烹饪方式对评分归类 funcConstructor(foods []string, cuisines []string, ratings []int) FoodRatings { f := FoodRatings{ Map: make(map[string]*FoodHeap), NameMap: make(map[string]*Food, len(foods)), } var ( food *Food h *FoodHeap has bool ) for idx := range foods { food = &Food { foods[idx], cuisines[idx], ratings[idx], 0, } f.NameMap[foods[idx]] = food
if h, has = f.Map[cuisines[idx]]; !has { h = &FoodHeap{} f.Map[cuisines[idx]] = h }
heap.Push(h, food) } return f }
func(this *FoodRatings) ChangeRating(food string, newRating int) { f := this.NameMap[food] h := this.Map[f.C] f.Rating = newRating
heap.Fix(h, f.Idx) }
func(this *FoodRatings) HighestRated(cuisine string) string { h := this.Map[cuisine] if h.Len() == 0 { return cuisine + "No exist" } return (*h)[0].Name }
func(this *MaxQueue) Pop_front() int { n := -1 iflen(this.q1) != 0{ n = this.q1[0] this.q1 = this.q1[1:] if this.max[0] == n{ this.max = this.max[1:] } } return n }
/** * Your MaxQueue object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Max_value(); * obj.Push_back(value); * param_3 := obj.Pop_front(); */