Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

     

Insert Delete GetRandom O(1) - LeetCode

Design a data structure that supports all following operations in average O(1) time.

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Algorithm:

The intuition here is whenever you want to achieve in less time, you have to sacrifice space. So we are gonna use extra space with hash table.

Delete from set

/** * Initialize your data structure here. */varRandomizedSet=function(){this.nums=newArray();this.locs=newObject();};/** * Inserts a value to the set. Returns true if the set did not already contain the specified element. * @param {number} val * @return {boolean} */RandomizedSet.prototype.insert=function(val){if(!(valinthis.locs)){this.nums.push(val);this.locs[val]=this.nums.length-1;returntrue;}returnfalse;};/** * Removes a value from the set. Returns true if the set contained the specified element. * @param {number} val * @return {boolean} */RandomizedSet.prototype.remove=function(val){if(valinthis.locs){letloc=this.locs[val];letlastEl=this.nums[this.nums.length-1];this.nums[loc]=lastEl;this.locs[lastEl]=loc;this.nums.pop();deletethis.locs[val];returntrue;}returnfalse;};/** * Get a random element from the set. * @return {number} */RandomizedSet.prototype.getRandom=function(){returnthis.nums[Math.floor(Math.random()*this.nums.length)];};

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Bangalore
  • Education
    Self Taught Developer
  • Joined

More fromSubramanya Chakravarthy

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp