Google/LintCode:M-Insert Delete GetRandom O(1)

来源:互联网 发布:广东省软件企业评估 编辑:程序博客网 时间:2024/06/05 08:41

题目


题目来源:Link


Design a data structure that supports all following operations in average O(1)time.

  • insert(val): Inserts an item val to the set if not already present.
  • remove(val): Removes an item val from the set if present.
  • getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
样例
// Init an empty set.RandomizedSet randomSet = new RandomizedSet();// Inserts 1 to the set. Returns true as 1 was inserted successfully.randomSet.insert(1);// Returns false as 2 does not exist in the set.randomSet.remove(2);// Inserts 2 to the set, returns true. Set now contains [1,2].randomSet.insert(2);// getRandom should return either 1 or 2 randomly.randomSet.getRandom();// Removes 1 from the set, returns true. Set now contains [2].randomSet.remove(1);// 2 was already in the set, so return false.randomSet.insert(2);// Since 2 is the only number in the set, getRandom always return 2.randomSet.getRandom();

分析


(1)添加和删除要做到O(1),肯定用Hash

(2)随机获得数据,肯定要随机数据的index,且要随机存取,则可以List、Vector

(3)将两者结合的关键是,在删除的时候,需要更新两者的index对应关系,巧妙的做法就是讲List的尾巴复制到要删除的index位置,更新尾巴在Hash中对应的Index,删除List的尾巴和Hash中要删除的元素即可


代码


public class RandomizedSet {        Map<Integer, Integer> map;    List<Integer> list;        Random rand = new Random();    public RandomizedSet() {        // do initialize if necessary        map = new HashMap<Integer, Integer>();        list = new ArrayList<Integer>();    }        // Inserts a value to the set    // Returns true if the set did not already contain the specified element or false    public boolean insert(int val) {        // Write your code here        if(!map.containsKey(val)){            int index = map.size();            map.put(val, index);            list.add(val);            return true;        }        return false;    }        // Removes a value from the set    // Return true if the set contained the specified element or false    public boolean remove(int val) {        // Write your code here        if(map.containsKey(val)){            int index = map.get(val);            int lastVal = list.get(list.size()-1);            list.set(index, lastVal);//把尾巴替换到删除的位置            list.remove(list.size()-1);//删除尾巴            map.put(lastVal, index);//修改尾巴对应的index            map.remove(val);//删除val                        return true;        }        return false;    }        // Get a random element from the set    public int getRandom() {        // Write your code here        return list.get(rand.nextInt(list.size()));    }}/** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param = obj.insert(val); * boolean param = obj.remove(val); * int param = obj.getRandom(); */