[LinkedIn]linked List data structure so that add/insert, remove, get random in O(1) constant time

Consider a data structure composed of a hashtable H and an array A. The hashtable keys are the elements in the data structure, and the values are their positions in the array.

  1. insert(value): append the value to array and let i be it’s index in A. Set H[value]=i.
  2. remove(value): We are going to replace the cell that contains value in A with the last element in A. let d be the last element in the array A at index m. let i be H[value], the index in the array of the value to be removed. Set A[i]=d, H[d]=i, decrease the size of the array by one, and remove value from H.
  3. contains(value): return H.contains(value)
  4. getRandomElement(): let r=random(current size of A). return A[r].
//ArrayList + HashMap
//remove的时候把最后一个元素拿过来补上
interface List<T> {
 public void add(T o); // add to the last
 public T get(int index); // get the index object
 public int size(); // return the size
 public boolean remove(T o); // remove the first o and return true; if not exist,
                             // return false.
}

public class ListImpl implements List<T> {
 private class ListNode {
   T val;
   ListNode prev, next;
   ListNode(T val) {
     this.val = val;
   }
 }
 Map<T, LinkedList<ListNode>> hm;
 ListNode dummyHead, dummyTail;

 public ListImpl() {
   hm = new HashMap<T, LinkedList<ListNode>>();
   dummyHead = new ListNode(null);
   dummyTail = new ListNode(null);
 }

 public void add(T o) {

 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值