当前位置:网站首页>Hash table: the time complexity of insert, delete and random access is O (1)
Hash table: the time complexity of insert, delete and random access is O (1)
2022-06-13 02:45:00 【Zeng Qiang】
subject
https://leetcode-cn.com/problems/FortPu/
Their thinking
See the time complexity O(1) You can think of arrays or hash tables .
The special situation here needs to be considered getRandom function , And return a random number with the same probability . So to achieve this goal , Can only return from the array , And the array has an index .
So the data structure we can design for this topic is :
Hashtable : The element to be modified is key, The index of the element is used as value.
Array : Used to hold elements , And the array index can be used to generate a random number , You can return a number with a random number as the index of the array .
How to use time complexity from an array O(1) To delete an element ?
The most error prone place here is to delete a number .
Delete a number from the array , You need to traverse the array once , To find the deleted number , This time complexity is O(n); So we have to use another technique :
First, the last number in the list and the number to be deleted ( We have used the hash table as the subscript value Save ) In exchange for . After exchanging , You can delete the last number of the list each time , In this way, the time complexity reaches O(1);
The specific code is as follows :
Code
class RandomizedSet {
// Hash table can be deleted , Inquire about O(1) Time complexity .
Map<Integer, Integer> numToLocation = null;
// Want to generate a random number with the same probability , You need a list index , The hash table does not have an index , We have to do this with arrays .
//Nums Save values inside . and HashMap Save the index with the value of .
ArrayList<Integer> nums = null;
/** Initialize your data structure here. */
public RandomizedSet() {
numToLocation = new HashMap<>();
nums = new ArrayList<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(numToLocation.containsKey(val)){
return false;
}
numToLocation.put(val, nums.size());
nums.add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!numToLocation.containsKey(val)) {
return false;
}
int location = numToLocation.get(val);
numToLocation.put(nums.get(nums.size() - 1), location);
numToLocation.remove(val);
nums.set(location, nums.get(nums.size() - 1));
nums.remove(nums.size() - 1);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
Random random = new Random();
int key = random.nextInt(nums.size());
return nums.get(key);
}
}
/** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
summary
This topic examines the properties of hash tables and arrays , Time complexity O(1). At the same time, how to delete a number of the array in combination with the hash table , And the time complexity O(1).
边栏推荐
- [reading paper] generate confrontation network Gan
- Modify the color of El input, textarea and El checkbox when they are disabled
- Principle and steps of principal component analysis (PCA)
- Special topic I of mathematical physics of the sprint strong foundation program
- js多种判断写法
- [reading papers] transformer miscellaneous notes, especially miscellaneous
- [life science] DNA extraction of basic biological experiments
- Ijkplayer source code - remuxing
- 智能安全配电装置如何减少电气火灾事故的发生?
- Ijkplayer source code ---packetqueue
猜你喜欢

Detailed explanation of handwritten numeral recognition based on support vector machine (Matlab GUI code, providing handwriting pad)

冲刺强基计划数学物理专题一
![[reading paper] generate confrontation network Gan](/img/88/950b47cac330f208c0c9e100f42b4f.jpg)
[reading paper] generate confrontation network Gan
![[data analysis and visualization] key points of data drawing 3- spaghetti map](/img/3d/ea832e67d22c62b07dc46cf49e50ba.jpg)
[data analysis and visualization] key points of data drawing 3- spaghetti map
![[data analysis and visualization] key points of data drawing 8- use of circular bar chart](/img/1f/232f2f0134867eeec3f1cfe005b2b5.jpg)
[data analysis and visualization] key points of data drawing 8- use of circular bar chart

Data warehouse notes | 5 factors that need attention for customer dimension modeling

Detailed explanation of data processing in machine learning (I) -- missing value processing (complete code attached)
![[reading papers] visual convolution zfnet](/img/01/4181f19b2d24b842488522c2001970.jpg)
[reading papers] visual convolution zfnet

Bi modal progressive mask attention for fine graded recognition
![[data analysis and visualization] key points of data drawing 5- the problem of error line](/img/d7/a54129d2c7bdf7caf764f6f8db9fc1.jpg)
[data analysis and visualization] key points of data drawing 5- the problem of error line
随机推荐
Superficial understanding of conditional random fields
Opencv 08 demonstrates the effect of opening and closing operations of erode, dilate and morphological function morphologyex.
nn. Conv2d and nn Convtranspose2d differences
Change tax for 2
微信云开发粗糙理解
Uni app Foundation
redis
A wechat app for shopping
Branch and bound method, example sorting
Ijkplayer source code - remuxing
Graduation project - campus old thing recycling system based on stm32
Linear, integer, nonlinear, dynamic programming
Huffman tree and its application
Vant realizes the adaptation of mobile terminal
Matlab: find the inner angle of n-sided concave polygon
[data analysis and visualization] key points of data drawing 9- color selection
Leetcode 926. Flip string to monotonically increasing [prefix and]
Redirection setting parameters -redirectattributes
Opencv 9 resize size change rotate rotate blur mean (blur)
String: number of substring palindromes