|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 23/03/2017. |
| 5 | + * Accepted |
| 6 | + */ |
| 7 | +public class RandomizedSet |
| 8 | +{ |
| 9 | + private Map<Integer, Integer> map; |
| 10 | + private List<Integer> list; |
| 11 | + private Random random; |
| 12 | + /** Initialize your data structure here. */ |
| 13 | + public RandomizedSet() |
| 14 | + { |
| 15 | + map = new HashMap<>(); |
| 16 | + list = new ArrayList<>(); |
| 17 | + random = new Random(); |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Main method |
| 22 | + * @param args |
| 23 | + * @throws Exception |
| 24 | + */ |
| 25 | + public static void main(String[] args) throws Exception |
| 26 | + { |
| 27 | + RandomizedSet rSet = new RandomizedSet(); |
| 28 | + System.out.println(rSet.getRandom()); |
| 29 | + System.out.println(rSet.insert(1)); |
| 30 | + System.out.println(rSet.insert(2)); |
| 31 | + System.out.println(rSet.insert(2)); |
| 32 | + System.out.println(rSet.insert(3)); |
| 33 | + System.out.println(rSet.remove(2)); |
| 34 | + System.out.println(rSet.insert(2)); |
| 35 | + System.out.println(rSet.getRandom()); |
| 36 | + System.out.println(rSet.insert(234)); |
| 37 | + System.out.println(rSet.insert(23)); |
| 38 | + System.out.println(rSet.insert(22)); |
| 39 | + System.out.println(rSet.getRandom()); |
| 40 | + System.out.println(rSet.remove(245)); |
| 41 | + System.out.println(rSet.remove(234)); |
| 42 | + System.out.println(rSet.getRandom()); |
| 43 | + } |
| 44 | + |
| 45 | + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ |
| 46 | + public boolean insert(int val) |
| 47 | + { |
| 48 | + if(!map.keySet().contains(val)) |
| 49 | + { |
| 50 | + int pos = list.size(); |
| 51 | + map.put(val, pos); |
| 52 | + list.add(val); |
| 53 | + return true; |
| 54 | + } |
| 55 | + return false; |
| 56 | + } |
| 57 | + |
| 58 | + /** Removes a value from the set. Returns true if the set contained the specified element. */ |
| 59 | + public boolean remove(int val) |
| 60 | + { |
| 61 | + if(map.containsKey(val)) |
| 62 | + { |
| 63 | + int size = list.size(); |
| 64 | + int posVal = map.get(val); |
| 65 | + if(posVal < (size - 1)) |
| 66 | + { |
| 67 | + int last = list.get(size - 1); |
| 68 | + map.put(last, posVal); |
| 69 | + list.set(posVal, last); |
| 70 | + } |
| 71 | + map.remove(val); |
| 72 | + list.remove(size - 1); |
| 73 | + return true; |
| 74 | + } |
| 75 | + return false; |
| 76 | + } |
| 77 | + |
| 78 | + /** Get a random element from the set. */ |
| 79 | + public int getRandom() |
| 80 | + { |
| 81 | + /*if(list.size() == 0) return 0; |
| 82 | + else if (list.size() == 1) return list.get(0);*/ |
| 83 | + return list.get(random.nextInt(list.size() - 1)); |
| 84 | + } |
| 85 | + |
| 86 | +} |
0 commit comments