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. nohup命令浅析

    要将一个命令放到后台执行,我们一般使用nohup sh command & &都知道是放到后台执行这个命令,那么nohup是做什么的? 这就要从unix的信号说起,unix的信号机制可 ...

  2. db2日常维护

    一. DB2日常维护操作 1.数据库的启动.停止.激活 db2 list active databases db2 active db 数据库名 db2start --启动 db2stop [forc ...

  3. 关于IE9中webdiriver使用autoit上传文件报错

    在ie9中, type="file"的元素是通过js打开的 webdirver结合autoit上传文件时,会报拒绝访问的错 sciTE编辑器中是这样写的: #include < ...

  4. 李洪强iOS经典面试题131

    培训机构量产iOS程序员,导致了现在iOS就业的浮躁和困难.但是技术好的人仍然不愁工作,而一些想进入行业捞一笔就走的人,势必在今年这种艰难就业形式下,被迫淘汰,转行. look.jpg 这张图是git ...

  5. Qt 按钮事件不响应

    在Qt中,我们设置好按钮的相应事件,连好信号槽,声明什么的也没什问题,但为什么点击按钮就是没有反应,检查了半天终于发现原来是子面板上也有一个相同名称的按钮,一般来说两个面板不为父子关系的时候,分别在不 ...

  6. jdbc模拟电话本。

    1 项目描述 该项目是用于日常生活中记录联系人信息的一款小工具. 实现了对联系人的姓名.年龄.性别.电话号码.住址的添加及修改.查找.删除.排序等功能.该项目是以windows控制台为运行平台,所有的 ...

  7. spring security动态管理资源结合自定义登录页面

    如果想将动态管理资源与自定义登录页面一起使用,最简单的办法就是在数据库中将登录页面对应的权限设置为IS_AUTHENTICATED_ANONYMOUSLY. 因此在数据库中添加一条资源信息. INSE ...

  8. ajaxfileupload.js支持多文件上传【转载】

    //修改前代码------- //var oldElement = jQuery('#' + fileElementId); //var newElement = jQuery(oldElement) ...

  9. sql 数据库 初级 个人学习总结(一)

    数据库个人总结(初级)1.增删改查 insert into 表名 values ('条件','条件2') delete from 表名 where 条件 update 表名 set=条件值 where ...

  10. Unity UGUI 裁剪TTF字体

    BitBucket上找到了一个perl工程,font-optimizer.拉取代码到本地.为了运行它,还需要装Perl解释器,可以在Perl的官网上下载ActivePerl.装好ActivePerl后 ...