Insert Delete GetRandom O(1)

http://www.lintcode.com/en/problem/insert-delete-getrandom-o1/
因为要求是o1,所以使用Map来存储。

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class RandomizedSet {
    private Map map;

    public RandomizedSet() {
        // do intialization if necessary
        map = new HashMap<>();
    }

    /*
     * @param val: a value to the set
     * @return: true if the set did not already contain the specified element or false
     */
    public boolean insert(int val) {
        // write your code here
        boolean b = map.containsKey(val);
        map.put(val, null);
        return b;
    }

    /*
     * @param val: 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
        boolean b = map.containsKey(val);
        map.remove(val);
        return b;
    }

    /*
     * @return: Get a random element from the set
     */
    public int getRandom() {
        // write your code here
        Object[] array = map.keySet().toArray();
        return (int) array[new Random().nextInt(array.length)];
    }
}

/**
 * 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();
 */

你可能感兴趣的:(Insert Delete GetRandom O(1))