leetcode 432. All O`one Data Structure

9 篇文章 0 订阅
3 篇文章 0 订阅

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.

解题思路:

插入删除能在O(1)时间完成的也就hash table了。所以用unordered_map<string , int>存储每个字符串对应的频次。因为需要根据频次返回最大频次和最小频次对应的字符串,所以用map<int , set<string>> 存储对应频次的所有字符串,因为map是根据key有序排列的,所以map的第一个和最后一个key分别是最小频次和最大频次;

class AllOne {
public:
    /** Initialize your data structure here. */
    AllOne() {
        
    }
    
    /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
    void inc(string key) 
    {
        if(keys.count(key)) 
        {
            fre[keys[key]].erase(key) ;
            if(fre[keys[key]].empty()) fre.erase(keys[key]) ;
        }
        keys[key]++ ;
        fre[keys[key]].insert(key) ;
    }
    
    /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
    void dec(string key) 
    {
        if(!keys.count(key)) return ;
        fre[keys[key]].erase(key) ;
        if(fre[keys[key]].empty()) fre.erase(keys[key]) ;
        if(--keys[key] == 0)
        {
            keys.erase(key) ;
        }
        else
        {
            fre[keys[key]].insert(key) ;
        }
    }
    
    /** Returns one of the keys with maximal value. */
    string getMaxKey() 
    {
        if(fre.empty()) return "" ;
        int n = fre.size() ;
        cout<<fre.begin()->first<<endl;
        return *((next(fre.begin() , n - 1)->second).begin()) ;
    }
    
    /** Returns one of the keys with Minimal value. */
    string getMinKey() {
        if(fre.empty()) return "" ;
        return *((fre.begin()->second).begin()) ;
    }
    
private :
    
    unordered_map<string , int> keys ;
    map<int , set<string>> fre ;
};

/**
 * 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值