|
| 1 | +package com.leetcode.JuneChallenge.week2; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Random; |
| 7 | + |
| 8 | +class RandomizedSet { |
| 9 | + private List<Integer> list; |
| 10 | + private HashMap<Integer, Integer> map; |
| 11 | + private Random rand; |
| 12 | + |
| 13 | + /** Initialize your data structure here. */ |
| 14 | + public RandomizedSet() { |
| 15 | + list = new ArrayList<Integer>(); |
| 16 | + map = new HashMap<Integer, Integer>(); |
| 17 | + rand = new Random(); |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Inserts a value to the set. Returns true if the set did not already contain |
| 22 | + * the specified element. |
| 23 | + */ |
| 24 | + public boolean insert(int val) { |
| 25 | + if (map.containsKey(val)) |
| 26 | + return false; |
| 27 | + |
| 28 | + list.add(val); |
| 29 | + map.put(val, list.size() - 1); |
| 30 | + return true; |
| 31 | + |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Removes a value from the set. Returns true if the set contained the specified |
| 36 | + * element. |
| 37 | + */ |
| 38 | + public boolean remove(int val) { |
| 39 | + if (!map.containsKey(val)) |
| 40 | + return false; |
| 41 | + |
| 42 | + int index = map.get(val); |
| 43 | + int valueAtLastIndex = list.get(list.size() - 1); |
| 44 | + |
| 45 | + list.set(index, valueAtLastIndex); |
| 46 | + map.put(valueAtLastIndex, index); |
| 47 | + list.remove(list.size() - 1); |
| 48 | + map.remove(val); |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + /** Get a random element from the set. */ |
| 53 | + public int getRandom() { |
| 54 | + |
| 55 | + return list.get(rand.nextInt(list.size())); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Your RandomizedSet object will be instantiated and called as such: |
| 61 | + * |
| 62 | + */ |
| 63 | + |
| 64 | +public class InsertDeleteGetRandom { |
| 65 | + |
| 66 | + public static void main(String[] args) { |
| 67 | + RandomizedSet obj = new RandomizedSet(); |
| 68 | + |
| 69 | + System.out.println(obj.insert(1)); |
| 70 | + System.out.println(obj.remove(2)); |
| 71 | + System.out.println(obj.insert(2)); |
| 72 | + System.out.println(obj.getRandom()); |
| 73 | + System.out.println(obj.remove(1)); |
| 74 | + System.out.println(obj.insert(2)); |
| 75 | + System.out.println(obj.getRandom()); |
| 76 | + |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments