Implement a data structure supporting the following operations:

Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.
GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".
Challenge: Perform all these in O(1) time complexity.

Solution: O(1) time complexity

解题思路主要参考了网友ivancjw的帖子,数据结构参考了https://discuss.leetcode.com/topic/65634/java-ac-all-strict-o-1-not-average-o-1-easy-to-read用bucket,思路是,我们建立一个次数分层的结构,次数多的在顶层,每一层放相同次数的key值,例如下面这个例子:

"A": 4, "B": 4, "C": 2, "D": 1

那么用我们设计的结构保存出来就是:

row0: val = 4, keys = {"A", "B"}
row1: val = 2, keys = {"C"}
row2: val = 1, keys = {"D"}

 public class AllOne {
public class Bucket {
int count;
Bucket prev;
Bucket next;
HashSet<String> keySet;
public Bucket(int num) {
this.count = num;
this.keySet = new HashSet<String>();
}
} Bucket head;
Bucket tail;
HashMap<String, Integer> keyCountMap;
HashMap<Integer, Bucket> countBucketMap; /** Initialize your data structure here. */
public AllOne() {
this.head = new Bucket(Integer.MIN_VALUE);
this.tail = new Bucket(Integer.MAX_VALUE);
head.next = tail;
tail.prev = head;
this.keyCountMap = new HashMap<String, Integer>();
this.countBucketMap = new HashMap<Integer, Bucket>();
} /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
public void inc(String key) {
if (keyCountMap.containsKey(key)) {
change(key, 1);
}
else {
keyCountMap.put(key, 1);
if (head.next.count != 1) { //dont have the 1 bucket
addBucketAfter(new Bucket(1), head);
countBucketMap.put(1, head.next);
}
head.next.keySet.add(key);
}
} /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
public void dec(String key) {
if (keyCountMap.containsKey(key)) {
int count = keyCountMap.get(key);
if (count == 1) {
keyCountMap.remove(key);
removeKeyFromBucket(countBucketMap.get(count), key);
}
else change(key, -1);
}
} /** Returns one of the keys with maximal value. */
public String getMaxKey() {
return tail.prev==head? "" : (String)tail.prev.keySet.iterator().next();
} /** Returns one of the keys with Minimal value. */
public String getMinKey() {
return head.next==tail? "" : (String)head.next.keySet.iterator().next();
} public void change(String key, int offset) {
//get count, update keyCountMap
int count = keyCountMap.get(key);
keyCountMap.put(key, count+offset); //get current bucket
Bucket curBucket = countBucketMap.get(count); //new bucket
Bucket newBucket;
if (countBucketMap.containsKey(count+offset)) {
newBucket = countBucketMap.get(count+offset);
}
else {
newBucket = new Bucket(count+offset);
countBucketMap.put(count+offset, newBucket);
addBucketAfter(newBucket, (offset==1? curBucket : curBucket.prev));
}
newBucket.keySet.add(key);
removeKeyFromBucket(curBucket, key);
} public void removeKeyFromBucket(Bucket cur, String key) {
cur.keySet.remove(key);
if (cur.keySet.size() == 0) {
removeBucketFromList(cur);
countBucketMap.remove(cur.count);
}
} public void removeBucketFromList(Bucket cur) {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
cur.next = null;
cur.prev = null;
} public void addBucketAfter(Bucket bucket, Bucket preBucket) {
bucket.prev = preBucket;
bucket.next = preBucket.next;
preBucket.next.prev = bucket;
preBucket.next = bucket;
}
} /**
* Your AllOne object will be instantiated and called as such:
* AllOne obj = new AllOne();
* obj.inc(key);
* obj.dec(key);
* String param_3 = obj.getMaxKey();
* String param_4 = obj.getMinKey();
*/

Solution 2: 如果不要求O(1)time, 这个用两个heap方法很常规

 public class AllOne {

     class Node{
String key;
int val;
public Node(String key, int val) {
this.key = key;
this.val = val;
}
}
/** Initialize your data structure here. */
HashMap<String, Node> map;
PriorityQueue<Node> minQ;
PriorityQueue<Node> maxQ;
public AllOne() {
map = new HashMap<String, Node>();
minQ = new PriorityQueue<Node>(new Comparator<Node>(){
public int compare(Node a, Node b) {
return a.val - b.val;
}
});
maxQ = new PriorityQueue<Node>(new Comparator<Node>(){
public int compare(Node a, Node b) {
return b.val - a.val;
}
});
} /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
public void inc(String key) {
if (!map.containsKey(key)) {
map.put(key, new Node(key, 1));
Node node = map.get(key);
minQ.add(node);
maxQ.add(node);
} else {
Node node = map.get(key);
minQ.remove(node);
maxQ.remove(node);
node.val++;
map.put(key, node);
minQ.add(node);
maxQ.add(node);
}
} /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
public void dec(String key) {
if (map.containsKey(key)) {
Node node = map.get(key);
if (node.val == 1) {
map.remove(key);
minQ.remove(node);
maxQ.remove(node);
} else {
minQ.remove(node);
maxQ.remove(node);
node.val--;
map.put(key, node);
minQ.add(node);
maxQ.add(node);
}
}
} /** Returns one of the keys with maximal value. */
public String getMaxKey() {
return maxQ.isEmpty() ? "" : maxQ.peek().key;
} /** Returns one of the keys with Minimal value. */
public String getMinKey() {
return minQ.isEmpty() ? "" : minQ.peek().key;
}
}

Leetcode: All O`one Data Structure的更多相关文章

  1. [LeetCode] All O`one Data Structure 全O(1)的数据结构

    Implement a data structure supporting the following operations: Inc(Key) - Inserts a new key with va ...

  2. [LeetCode] Two Sum III - Data structure design 两数之和之三 - 数据结构设计

    Design and implement a TwoSum class. It should support the following operations:add and find. add - ...

  3. LeetCode Two Sum III - Data structure design

    原题链接在这里:https://leetcode.com/problems/two-sum-iii-data-structure-design/ 题目: Design and implement a ...

  4. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  5. Java for LeetCode 211 Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word)bool search(wo ...

  6. leetcode@ [211] Add and Search Word - Data structure design

    https://leetcode.com/problems/add-and-search-word-data-structure-design/ 本题是在Trie树进行dfs+backtracking ...

  7. leetcode面试准备:Add and Search Word - Data structure design

    leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...

  8. LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$

    Design and implement a TwoSum class. It should support the following operations: add and find. add - ...

  9. 【LeetCode】170. Two Sum III – Data structure design

    Difficulty:easy  More:[目录]LeetCode Java实现 Description Design and implement a TwoSum class. It should ...

随机推荐

  1. IOS启动顺序

    一.UIApplicationMain的执行步骤1.创建一个UIApplication对象,一个程序对应一个UIApplication对象(单例),UIApplication对象是程序的象征2.接下来 ...

  2. linux下的crontab服务

    linux下的crontab服务:1.crontab 是用来让使用者在固定时间或固定间隔执行程序之用在linux平台上如果需要实现任务调度功能可以编写cron脚本来实现.以某一频率执行任务linux缺 ...

  3. Optimizely:在线网站A/B测试平台

    Optimizely:在线网站A/B测试平台是一家提供 A/B 测试服务的公司.A/B 测试能够对比不同版本的设计,选取更吸引用户眼球的那一款,从而带来更为优化的个人体验.让网站所有者易于对不同版本的 ...

  4. 可能碰到的iOS笔试面试题(4)--C语言

    可能碰到的iOS笔试面试题(4)--C语言 可能碰到的iOS笔试面试题(4)--C语言 C语言,开发的基础功底,iOS很多高级应用都要和C语言打交道,所以,C语言在iOS开发中的重要性,你懂的.里面的 ...

  5. android api汇集

    参考文章: 知乎-想写个 App 练手,有什么有趣的 API 接口推荐吗? 使用 Espresso 和 Dagger 测试网络服务 http://developer.simsimi.com/apps# ...

  6. AOP 学习

    学习 Spring.Net 的AOP 的时候,在做一个简单的测试例子的时候,配置文件和代码逻辑都是没问题的,但始终报这样一个异常: 无法将类型为“CompositionAopProxy_1e76f37 ...

  7. 手机自带的显示基站命令(android手机定位,iphone基站定位)

    手机自带的显示基站命令(安卓手机定位,苹果手机基站定位) 分类: 通信和网络2012-02-07 17:48 1734人阅读 评论(0) 收藏 举报 手机htciphone中兴三星网络 安卓手机自带快 ...

  8. MacPort 的使用

    MacPorts 的安装和使用   官网下载最版本的 安装包   自动安装  可能会出现很慢的情况   设置环境变量   vim ~/.bash_profile      i  插入修改  :wq 保 ...

  9. Python开发问题和解决方案汇集

    1.Sublime Text中用Tab批量替换空格Whitespace缩进:Ctrl+A全选代码,Ctrl+Shift+P打开下拉框,输入indent,找到Convert indentation to ...

  10. rbd命令

    chen@admin-node:~$ rbd --help usage: rbd [-n <auth user>] [OPTIONS] <cmd> ... where 'poo ...