Insert Delete Getrandom O(1) || Leetcode

preview_player
Показать описание

NADOS also enables doubt support, career opportunities and contests besides free of charge content for learning. Pepcoding has taken the initiative to provide counselling and learning resources to all curious, skillful and dedicated Indian coders. This video is part of the series to impart industry-level web development and programming skills in the community.

 

We also provide professional courses with live classes and placement opportunities.

 

.

.

.

Happy Programming !!! Pep it up

.

.

.

#pepcoding #code #coder #codinglife #programming #coding #java #freeresources #datastrucutres #pepcode #competitive #competitiveprogramming #softwareengineer #engineering #engineer
Рекомендации по теме
Комментарии
Автор

here hashmap is used only for search whole work is done by array

josephstark
Автор

HashMap<Integer, Integer> map;
ArrayList<Integer> li;

public RandomizedSet() {
map = new HashMap<>();
li = new ArrayList<>();
}

public boolean insert(int val) {
if (map.containsKey(val))
return false;

map.put(val, li.size());
li.add(val);
return true;
}

public boolean remove(int val) {
if (!map.containsKey(val))
return false;

int idxToRemove = map.get(val);
int lastVal = li.get(li.size() - 1);
li.set(idxToRemove, lastVal);
map.put(lastVal, idxToRemove);

map.remove(val);
li.remove(li.size() - 1);

return true;
}

public int getRandom() {
int randomIdx = (int) (Math.random() * li.size());
return li.get(randomIdx);
}we dont need 3rd var

amCoder
welcome to shbcf.ru