432. All O`one Data Structure

来源:互联网 发布:excel数据拆分 编辑:程序博客网 时间:2024/06/05 19:37

Implement a data structure supporting the following operations:

  1. 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.
  2. 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.
  3. GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
  4. 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.


思路来自

https://discuss.leetcode.com/topic/63683/0ms-all-in-o-1-with-detailed-explantation


The main idea is to maintain an ordered two-dimensional doubly-linked list (let's call it matrix for convenience), of which each row is corresponding to a value and all of the keys in the same row have the same value.

Suppose we get the following key-value pairs after some increment operations. ("A": 4 means "A" is increased four times so its value is 4, and so on.)

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

Then one possible matrix may look like this:

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

If we can guarantee the rows are in descending order in terms of value, then GetMaxKey()/GetMinKey() will be easy to implement in O(1) time complexity. Because the first key in the first row will always has the maximal value, and the first key in the last row will always has the minimal value.

Once a key is increased, we move the key from current row to last row if last_row.val = current_row.val + 1. Otherwise, we insert a new row before current row with vallue current_row.val + 1, and move the key to to the new row. The logic of decrement operation is similar. Obviously, by doing this, the rows will keep its descending order.

For example, after Inc("D"), the matrix will become

row0: val = 4, strs = {"A", "B"}row1: val = 2, strs = {"C", "D"}

Inc("D") again

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

Now the key problem is how to maintain the matrix in O(1) runtime when increase/decrease a key by 1.

The answer is hash map. By using a hash map to track the position of a key in the matrix, we can access a key in the matrix in O(1). And since we use linked list to store the matrix, thus insert/move operations will all be O(1).

The psudocode of Inc() is as follows(Dec() is similar).

if the key isn't in the matrix:    if the matrix is empty or the value of the last row isn't 1:        insert a new row with value 1 to the end of the matrix, and put the key in the new row;    else:        put the key in the last row of the matrix;else:    if the key is at the first row or last_row.value != current_row.value + 1:        insert a new row before current row, with value current_row.value + 1, and move the key to the new row;    else:        move the key from current row to last row;



hashmap用于常规方法的数据存取、加减,vhashmap将数值和双向链表建立映射关系,即上面分析的“垂直”结构,使用手写双向链表


public class AllOne {    /** Initialize your data structure here. */HashMap<String, Integer> hashmap;dLinkedlist<Integer> head,tail;HashMap<Integer, dLinkedlist<Integer>> vhashmap;    public AllOne() {    hashmap=new HashMap<>();    head=new dLinkedlist<Integer>();    tail=new dLinkedlist<Integer>();    head.insertafter(head, tail);    vhashmap=new HashMap<>();    }        /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */public void inc(String key){Integer count_pre = hashmap.get(key);if (count_pre == null)hashmap.put(key, 1);else{hashmap.put(key, count_pre + 1);}int count_now = hashmap.get(key);if (count_pre == null){if (!vhashmap.containsKey(1)){dLinkedlist<Integer> dNode = new dLinkedlist<Integer>();vhashmap.put(1, dNode);head.insertafter(head, dNode);}vhashmap.get(1).hashset.add(key);} else{dLinkedlist<Integer> oldNode = vhashmap.get(count_pre);dLinkedlist<Integer> newNode = vhashmap.get(count_now);if (newNode == null){dLinkedlist<Integer> dNode = new dLinkedlist<Integer>();vhashmap.put(count_now, dNode);oldNode.insertafter(oldNode, dNode);}vhashmap.get(count_now).hashset.add(key);oldNode.hashset.remove(key);if(oldNode.hashset.isEmpty()){vhashmap.remove(count_pre);oldNode.delete(oldNode);}}}        /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */public void dec(String key){if (!hashmap.containsKey(key))return;int count_pre=hashmap.get(key);int count_now=count_pre-1;if(count_now==0)hashmap.remove(key);else {hashmap.put(key, count_now);}dLinkedlist<Integer> oldNode=vhashmap.get(count_pre);dLinkedlist<Integer> newNode=vhashmap.get(count_now);if(count_pre==1){oldNode.hashset.remove(key);if(oldNode.hashset.isEmpty()){oldNode.delete(oldNode);vhashmap.remove(1);}}else {if(newNode==null){dLinkedlist<Integer> dNode=new dLinkedlist<Integer>();vhashmap.put(count_now, dNode);dLinkedlist<Integer> prevNode=oldNode.prev;prevNode.insertafter(prevNode, dNode);}vhashmap.get(count_now).hashset.add(key);oldNode.hashset.remove(key);if(oldNode.hashset.isEmpty()){vhashmap.remove(count_pre);oldNode.delete(oldNode);}}}        /** Returns one of the keys with maximal value. */    public String getMaxKey()    {        if(hashmap.isEmpty())        return "";        return tail.prev.hashset.iterator().next();    }        /** Returns one of the keys with Minimal value. */    public String getMinKey()    {        if(hashmap.isEmpty())        return "";        return head.next.hashset.iterator().next();    }}class dLinkedlist <T>{HashSet<String> hashset;dLinkedlist<T> prev;dLinkedlist<T> next;public dLinkedlist(){hashset=new HashSet<>();// TODO Auto-generated constructor stub}public void delete(dLinkedlist<T> node){node.prev.next=node.next;if(node.next!=null)node.next.prev=node.prev;node.prev=null;node.next=null;}public dLinkedlist<T> insertafter(dLinkedlist<T> node,dLinkedlist<T> n){n.prev=node;n.next=node.next;node.next=n;if(n.next!=null)n.next.prev=n;return n;}@Overridepublic String toString(){// TODO Auto-generated method stubStringBuilder sb=new StringBuilder();for(String s :hashset)sb.append(s).append('|');return sb.toString();}}/** * 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(); */


0 0
原创粉丝点击