码迷,mamicode.com
首页 > 其他好文 > 详细

p145 支持随机获取元素的集合(leetcode 380)

时间:2020-04-18 22:59:21      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:element   you   removes   boolean   move   集合   ini   data   leetcode   

一:解题思路

二:完整代码示例 (C++版和Java版)

C++:

class RandomizedSet 
{
private:
    map<int, int> m_map;
    vector<int> m_data;
public:
    /** Initialize your data structure here. */
    RandomizedSet() {

    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) 
    {
        if (m_map.count(val) != 0) return false;
        m_data.push_back(val);
        m_map[val] = m_data.size() - 1;

        return true;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) 
    {
        if (m_map.count(val) == 0) return false;
        int idx = m_map[val];
        int lastVal = m_data[m_data.size()-1];
        m_data[idx] = lastVal;
        m_data.pop_back();
        m_map[lastVal] = idx;
        m_map.erase(val);

        return true;
    }

    /** Get a random element from the set. */
    int getRandom() 
    {
        int idx = rand() % (m_data.size());

        return m_data[idx];
    }
};

Java:

class RandomizedSet
    {
        private Map<Integer,Integer> m_map=new HashMap<>();
        private List<Integer> m_data=new ArrayList<>();
        private Random RANDOM=new Random();
        /** Initialize your data structure here. */
        public RandomizedSet() {

        }

        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val)
        {
               if(m_map.containsKey(val)) return false;
               m_data.add(val);
               m_map.put(val,m_data.size()-1);
               return true;
        }

        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val)
        {
               if(!m_map.containsKey(val)) return false;
               int idx=m_map.get(val);
               int lastVal=m_data.get(m_data.size()-1);
               m_data.set(idx,lastVal);
               m_data.remove(m_data.size()-1);
               m_map.put(lastVal,idx);
               m_map.remove(val);
               
               return true;
        }

        /** Get a random element from the set. */
        public int getRandom() 
        {
               int idx=RANDOM.nextInt(m_data.size());
               
               return m_data.get(idx);
        }
    }

 

p145 支持随机获取元素的集合(leetcode 380)

标签:element   you   removes   boolean   move   集合   ini   data   leetcode   

原文地址:https://www.cnblogs.com/repinkply/p/12728475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!