type AllOne struct { keyCountMap map[string]int// Key to count mapping countKeysMap map[int]map[string]struct{} // Count to keys mapping countList *list.List // Sorted list of counts }
// Decrease the count for the key if currentCount == 1 { delete(ao.keyCountMap, key) } else { ao.keyCountMap[key] = currentCount - 1 ao.countKeysMap[currentCount-1][key] = struct{}{} }
// Remove key from the old count delete(ao.countKeysMap[currentCount], key) iflen(ao.countKeysMap[currentCount]) == 0 { delete(ao.countKeysMap, currentCount) }
// Add key to the new count if not zero if currentCount > 1 { if _, exists := ao.countKeysMap[currentCount-1]; !exists { ao.countKeysMap[currentCount-1] = make(map[string]struct{}) } ao.countKeysMap[currentCount-1][key] = struct{}{} } }
func(ao *AllOne) GetMaxKey() string { if ao.countList.Back() == nil { return"" } for key := range ao.countKeysMap[ao.countList.Back().Value.(int)] { return key // Return any key from the largest count } return"" }
func(ao *AllOne) GetMinKey() string { if ao.countList.Front() == nil { return"" } for key := range ao.countKeysMap[ao.countList.Front().Value.(int)] { return key // Return any key from the smallest count } return"" }
funcmain() { // Usage example allOne := Constructor() allOne.Inc("hello") allOne.Inc("world") allOne.Inc("hello") println(allOne.GetMaxKey()) // Should print "hello" println(allOne.GetMinKey()) // Should print "world" allOne.Dec("hello") println(allOne.GetMaxKey()) // Should print "hello" or "world" println(allOne.GetMinKey()) // Should print "hello" or "world" }
注意:上面的代码展示了数据结构的基本框架和 Inc、Dec 方法的逻辑,但是它并没有完全实现所有功能,特别是双向链表的部分和维护最小最大计数的精确逻辑。在实际应用中,你需要进一步完善 Inc 和 Dec 方法中对双向链表的操作,以确保可以在 O(1) 时间复杂度内找到最小和最大的计数值。这个实现更侧重于思路展示,而不是一个即插即用的解决方案。
fninc(&mutself, key: String) { letcount = self.count_map.entry(key.clone()).or_insert(0); // Remove from the current bucket self.bucket_map.entry(*count).and_modify(|v| { v.retain(|k| k != &key); if v.is_empty() { self.bucket_map.remove(count); } });
// Increment count and add to the new bucket *count += 1; self.bucket_map.entry(*count).or_insert_with(Vec::new).push(key); }
fndec(&mutself, key: String) { ifletSome(count) = self.count_map.get_mut(&key) { // Remove from the current bucket self.bucket_map.entry(*count).and_modify(|v| { v.retain(|k| k != &key); if v.is_empty() { self.bucket_map.remove(count); } });
// Decrement count and add to the new bucket if count > 0 *count -= 1; if *count > 0 { self.bucket_map.entry(*count).or_insert_with(Vec::new).push(key); } else { // Remove key from count_map if count becomes 0 self.count_map.remove(&key); } } }