382. Linked List Random Node
class Solution { ListNode node; Random random; /** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ public Solution(ListNode head) { node = head; random = new Random(); } /** Returns a random node's value. */ public int getRandom() { ListNode candidate = node; int result = candidate.val; int count = 0; while(true){ if(candidate == null) break; if(random.nextInt(++count) == 0) result = candidate.val; candidate = candidate.next; } return result; } }
380. Insert Delete GetRandom O(1)
class RandomizedSet { ArrayList<Integer> nums; HashMap<Integer, Integer> locs; Random rand = new Random(); /** Initialize your data structure here. */ public RandomizedSet() { nums = new ArrayList<Integer>(); locs = new HashMap<Integer, Integer>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { boolean contain = locs.containKey(val); if( contain ) return false; locs.put(val, nums.size()); nums.add(val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { boolean contain = locs.containKey(val); if( !contain ) return false; int loc = locs.get(val); if(loc < nums.size() - 1){// not the last one than swap the last one with this val int lastOneVal = nums.get(nums.size() - 1); nums.set(loc, lastOneVal); locs.put(lastOneVal, loc); } locs.remove(val); nums.remove(nums.size() - 1); return true; } /** Get a random element from the set. */ public int getRandom() { retrn nums.get(rand.nextInt(num.size())); } }