当前位置:网站首页>[high frequency interview questions] difficulty 2.5/5, simple combination of DFS trie template level application questions
[high frequency interview questions] difficulty 2.5/5, simple combination of DFS trie template level application questions
2022-07-07 13:46:00 【Gong Shui Sanye's Diary of writing questions】
Title Description
This is a LeetCode Upper 「677. Key value mapping 」 , The difficulty is 「 secondary 」.
Tag : 「 Dictionary tree 」、「DFS」、「 Hashtable 」
Achieve one MapSum class , Two methods are supported ,insert and sum:
MapSum()initializationMapSumobjectvoid insert(String key, int val)Insertkey-valKey value pair , Strings represent keyskey, Integers represent valuesval. If keykeyAlready exist , Then the original key value pair will be replaced by the new key value pair .int sum(string prefix)Returns all with this prefixprefixKey at the beginningkeyThe sum of the values of .
Example :
Input :
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output :
[null, null, 3, null, 5]
explain :
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);
mapSum.sum("ap"); // return 3 (apple = 3)
mapSum.insert("app", 2);
mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)
Tips :
keyandprefixIt's only made up of lowercase letters1 <= val <= 1000Call at most 50Timeinsertandsum
Trie + DFS
From the need to achieve 「 Store string ( The mapping relationship )」 and 「 Retrieve the sum of a string prefix 」 Look at , You can know that this is related to Related topics , I don't know yet Students can look at the front : Realization Trie ( Prefix tree ) .
Consider how to implement two operations :
insert: In the basic Just expand on the basis of the insertion operation . The only difference from the regular insert operation is , You can't simply record the end position of the word , And store Corresponding How much is the . Specifically, we can useintAn array of types To replace the originalbooleanAn array of types ;sum: Enter the parameter first Search the dictionary tree , Use after reaching the tailDFSSearch all the following schemes , And accumulate the results .
Code (static See , Avoid every sample new Big array ):
class MapSum {
int[][] tr = new int[2510][26];
int[] hash = new int[2510];
int idx;
public void insert(String key, int val) {
int p = 0;
for (int i = 0; i < key.length(); i++) {
int u = key.charAt(i) - 'a';
if (tr[p][u] == 0) tr[p][u] = ++idx;
p = tr[p][u];
}
hash[p] = val;
}
public int sum(String prefix) {
int p = 0;
for (int i = 0; i < prefix.length(); i++) {
int u = prefix.charAt(i) - 'a';
if (tr[p][u] == 0) return 0;
p = tr[p][u];
}
return dfs(p);
}
int dfs(int p) {
int ans = hash[p];
for (int u = 0; u < 26; u++) {
if (tr[p][u] != 0) ans += dfs(tr[p][u]);
}
return ans;
}
}
class MapSum {
static int[][] tr = new int[2510][26];
static int[] hash = new int[2510];
static int idx;
public MapSum() {
for (int i = 0; i <= idx; i++) Arrays.fill(tr[i], 0);
Arrays.fill(hash, 0);
idx = 0;
}
public void insert(String key, int val) {
int p = 0;
for (int i = 0; i < key.length(); i++) {
int u = key.charAt(i) - 'a';
if (tr[p][u] == 0) tr[p][u] = ++idx;
p = tr[p][u];
}
hash[p] = val;
}
public int sum(String prefix) {
int p = 0;
for (int i = 0; i < prefix.length(); i++) {
int u = prefix.charAt(i) - 'a';
if (tr[p][u] == 0) return 0;
p = tr[p][u];
}
return dfs(p);
}
int dfs(int p) {
int ans = hash[p];
for (int u = 0; u < 26; u++) {
if (tr[p][u] != 0) ans += dfs(tr[p][u]);
}
return ans;
}
}
Time complexity : Make The maximum length of is , The maximum number of calls is , The character set size is ( This topic Fixed for ), insertThe complexity of the operation is ; fromDFSFrom the perspective of ,sumThe complexity of the operation is , But in fact , For this problem, there is a clear upper bound on the amount of calculation , The complexity of searching all grids isSpatial complexity :
Trie Record the prefix string sum
To reduce sum The complexity of the operation , We can do it in insert Record at the same time during operation ( Add up ) The sum of each prefix .
Code (static See , Avoid every sample new Big array ):
class MapSum {
int N = 2510;
int[][] tr = new int[N][26];
int[] hash = new int[N];
int idx;
Map<String, Integer> map = new HashMap<>();
public void insert(String key, int val) {
int _val = val;
if (map.containsKey(key)) val -= map.get(key);
map.put(key, _val);
for (int i = 0, p = 0; i < key.length(); i++) {
int u = key.charAt(i) - 'a';
if (tr[p][u] == 0) tr[p][u] = ++idx;
p = tr[p][u];
hash[p] += val;
}
}
public int sum(String prefix) {
int p = 0;
for (int i = 0; i < prefix.length(); i++) {
int u = prefix.charAt(i) - 'a';
if (tr[p][u] == 0) return 0;
p = tr[p][u];
}
return hash[p];
}
}
class MapSum {
static int N = 2510;
static int[][] tr = new int[N][26];
static int[] hash = new int[N];
static int idx;
static Map<String, Integer> map = new HashMap<>();
public MapSum() {
for (int i = 0; i <= idx; i++) Arrays.fill(tr[i], 0);
Arrays.fill(hash, 0);
idx = 0;
map.clear();
}
public void insert(String key, int val) {
int _val = val;
if (map.containsKey(key)) val -= map.get(key);
map.put(key, _val);
for (int i = 0, p = 0; i < key.length(); i++) {
int u = key.charAt(i) - 'a';
if (tr[p][u] == 0) tr[p][u] = ++idx;
p = tr[p][u];
hash[p] += val;
}
}
public int sum(String prefix) {
int p = 0;
for (int i = 0; i < prefix.length(); i++) {
int u = prefix.charAt(i) - 'a';
if (tr[p][u] == 0) return 0;
p = tr[p][u];
}
return hash[p];
}
}
Time complexity : Make The maximum length of is , insertThe complexity of the operation is ;sumThe complexity of the operation isSpatial complexity : Make The maximum length of is , The maximum number of calls is , The character set size is ( This topic Fixed for ), The complexity is
Last
This is us. 「 Brush through LeetCode」 The first of the series No.677 piece , The series begins with 2021/01/01, As of the start date LeetCode I have in common 1916 questions , Part of it is a locked question , We will finish all the questions without lock first .
In this series , In addition to explaining the idea of solving problems , And give the most concise code possible . If the general solution is involved, there will be corresponding code templates .
In order to facilitate the students to debug and submit code on the computer , I've built a warehouse :https://github.com/SharingSource/LogicStack-LeetCode .
In the warehouse address , You can see the links to the series 、 The corresponding code of the series 、LeetCode Links to the original problem and other preferred solutions .
More, more, more popular 「 written examination / interview 」 Relevant information can be found in the beautifully arranged Gather new bases
边栏推荐
- [QNX hypervisor 2.2 user manual]6.3.4 virtual register (guest_shm.h)
- QQ的药,腾讯的票
- flask session伪造之hctf admin
- Write it down once Net a new energy system thread surge analysis
- 最佳实践 | 用腾讯云AI意愿核身为电话合规保驾护航
- Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
- LeetCode简单题分享(20)
- User management summary of mongodb
- 【日常训练--腾讯精选50】231. 2 的幂
- 2022-7-6 Leetcode 977. Square of ordered array
猜你喜欢
![[dark horse morning post] Huawei refutes rumors about](/img/d7/4671b5a74317a8f87ffd36be2b34e1.jpg)
[dark horse morning post] Huawei refutes rumors about "military master" Chen Chunhua; Hengchi 5 has a pre-sale price of 179000 yuan; Jay Chou's new album MV has played more than 100 million in 3 hours

LED light of single chip microcomputer learning notes

ESP32构解工程添加组件

Milkdown control icon

MongoDB内部的存储原理

Cinnamon taskbar speed

Leecode3. Longest substring without repeated characters

Navicat运行sql文件导入数据不全或导入失败

Fast development board pinctrl and GPIO subsystem experiment for itop-imx6ull - modify the device tree file

.net core 关于redis的pipeline以及事务
随机推荐
566. Reshaping the matrix
数据库系统概论-第一章绪论【概念模型、层次模型和三级模式(外模式、模式、内模式)】
MongoDB优化的几点原则
数字ic设计——SPI
High end for 8 years, how is Yadi now?
[dark horse morning post] Huawei refutes rumors about "military master" Chen Chunhua; Hengchi 5 has a pre-sale price of 179000 yuan; Jay Chou's new album MV has played more than 100 million in 3 hours
Xshell connection server changes key login to password login
Redis只能做缓存?太out了!
2022-7-6 Leetcode27.移除元素——太久没有做题了,为双指针如此狼狈的一天
Mongodb command summary
记一次 .NET 某新能源系统 线程疯涨 分析
How far can it go to adopt a cow by selling the concept to the market?
Introduction and basic use of stored procedures
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array
[daily training] 648 Word replacement
JS function returns multiple values
Clion mingw64 Chinese garbled code
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
Flink | multi stream conversion