657

来源:互联网 发布:java 数据库 proxy 编辑:程序博客网 时间:2024/06/08 13:25

2017.9.12

。。。。。感觉自己又违背了这题的初衷。

网上很多方法是将HashMap 和 List 结合使用的。

一个用来保证在添加和删除时的速度,

一个用来保证在生成随机谁时的速度。

道理我都懂啊,可是为什么只用ArrayList就可以了呢。

只是ArrayList.remove的时候。如果参数类型是object才会移除这个数据。如果参数类型是int型的话,就会int 就会作为index了。

public class RandomizedSet {    public ArrayList<Integer> list;    public Random r;public RandomizedSet() {        list = new ArrayList<Integer>();        r = new Random();    }        // 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(list.contains(val)){    return false;    }    else{    list.add(val);    return true;    }    }        // 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(!list.contains(val)){    return false;    }    else{    list.remove(Integer.valueOf(val));    return true;    }    }        // Get a random element from the set    public int getRandom() {        // Write your code here        int index = r.nextInt(list.size());    return list.get(index);    }}/** * 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(); */



原创粉丝点击