알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 06월 17일]
Leetcode - Insert Delete GetRandom O(1)
문제: LeetCode - 380. Insert Delete GetRandom O(1)
- O(1) 의 시간복잡도를 가지는
insert(), remove(), getRandom() 가진 set을 디자인하는 문제
- hashMap과 Array를 활용하여 풀이
코드
var RandomizedSet = function () {
this.map = new Map();
this.array = [];
};
RandomizedSet.prototype.insert = function (val) {
if (this.map.has(val)) return false;
this.map.set(val, this.map.size);
this.array.push(val);
return true;
};
RandomizedSet.prototype.remove = function (val) {
const currRemoveIdx = this.map.get(val);
if (
typeof currRemoveIdx === 'undefined' ||
typeof currRemoveIdx === 'null'
)
return false;
const arrLastIdx = this.array.length - 1;
if (currRemoveIdx !== arrLastIdx) {
const arrLastItem = this.array[arrLastIdx];
this.array[currRemoveIdx] = arrLastItem;
this.map.set(arrLastItem, currRemoveIdx);
}
this.map.delete(val);
this.array.pop();
return true;
};
RandomizedSet.prototype.getRandom = function () {
const randomIdx = Math.floor(Math.random() * this.array.length);
return this.array[randomIdx];
};
class RandomizedSet {
constructor() {
this.map = new Map();
this.array = [];
}
insert = (val) => {
if (this.map.has(val)) return false;
this.map.set(val, this.map.size);
this.array.push(val);
return true;
};
remove = (val) => {
const currRemoveIdx = this.map.get(val);
if (
typeof currRemoveIdx === 'undefined' ||
typeof currRemoveIdx === 'null'
)
return false;
const arrLastIdx = this.array.length - 1;
if (currRemoveIdx !== arrLastIdx) {
const arrLastItem = this.array[arrLastIdx];
this.array[currRemoveIdx] = arrLastItem;
this.map.set(arrLastItem, currRemoveIdx);
}
this.map.delete(val);
this.array.pop();
return true;
};
getRandom = () =>
this.array[Math.floor(Math.random() * this.array.length)];
}
const rm = new RandomizedSet();
rm.insert(0);
rm.insert(1);
rm.remove(0);
rm.insert(2);
rm.remove(1);
rm.getRandom();
참고 자료
강의
알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 06월 17일]
Leetcode - Insert Delete GetRandom O(1)
문제: LeetCode - 380. Insert Delete GetRandom O(1)
insert(),remove(),getRandom()가진 set을 디자인하는 문제코드
참고 자료
강의