LeetCode 380---Insert Delete GetRandom O(1)
2016-12-28 22:00
381 查看
题目链接:
LeetCode 380—Insert Delete GetRandom O(1)
AC代码:
LeetCode 380—Insert Delete GetRandom O(1)
AC代码:
package com.leetcode.arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class Problem380 { HashMap<Integer,Integer> map = new HashMap<>(); ArrayList<Integer> arr = new ArrayList<>(); /** Initialize your data structure here. */ public Problem380() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)){ map.put(val,1); arr.add(val); return true; } return false; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)){ map.remove(val); arr.remove(arr.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { if(arr.size() != 0){ Random rm=new Random(); int val = rm.nextInt(arr.size()); return arr.get(val); } return 0; } }
相关文章推荐
- LeetCode 380: Insert Delete GetRandom O(1)
- Leetcode 380 Insert Delete GetRandom O(1)
- leetcode(380). Insert Delete GetRandom O(1)
- LeetCode[380] Insert Delete GetRandom O(1)
- LeetCode-Insert Delete GetRandom O(1) - Duplicates allowed
- Leetcode 之 Insert Delete GetRandom O(1)
- Leetcode: Insert Delete GetRandom O(1) - Duplicates allowed
- Leetcode Insert Delete GetRandom O(1) Duplicates allowed and Not allowed
- 380. Insert Delete GetRandom O(1)
- HashTable-380-Insert Delete GetRandom O(1)
- LeetCode:381 Insert Delete GetRandom O(1)
- leetcode之 Insert Delete GetRandom O(1)
- LeetCode 381---Insert Delete GetRandom O(1) - Duplicates allowed
- [LeetCode] Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复
- leetcode之Insert Delete GetRandom O(1) 问题
- LeetCode Insert Delete GetRandom O(1)
- 380. Insert Delete GetRandom O(1)
- 380. Insert Delete GetRandom O(1)
- LeetCode Insert Delete GetRandom O(1) - Duplicates allowed
- LeetCode Insert Delete GetRandom O(1)