探险营地
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 137 ms, 内存: 24.9 MB
/*
* 思路:
* 1. 用一个Set存储初始已知的营地。
* 2. 遍历每次探险记录,计算每次新发现的营地数量。
* 3. 找出新发现营地最多且索引最小的那次探险。
* 4. 使用Java Stream进行操作。
*/
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ExpeditionSolutionStream {
public static int findExpeditionWithMostNewCamps(String[] expeditions) {
if (expeditions.length == 0) return -1;
Set<String> knownCamps = Arrays.stream(expeditions[0].split("->")).collect(Collectors.toSet());
int[] maxNewCamps = {0};
int[] resultIndex = {-1};
for (int i = 1; i < expeditions.length; i++) {
Set<String> newCamps = Arrays.stream(expeditions[i].split("->"))
.filter(camp -> !camp.isEmpty() && !knownCamps.contains(camp))
.collect(Collectors.toSet());
if (newCamps.size() > maxNewCamps[0]) {
maxNewCamps[0] = newCamps.size();
resultIndex[0] = i;
}
knownCamps.addAll(newCamps);
}
return resultIndex[0];
}
public static void main(String[] args) {
String[] expeditions = {"leet->code","leet->code->Campsite->Leet","leet->code->leet->courier"};
System.out.println(findExpeditionWithMostNewCamps(expeditions)); // 输出 1
}
}
解释
方法:
这个题解的思路是首先将第一个探险记录中的所有营地名存储到一个集合中,表示这些营地已经被发现。然后,从第二个记录开始遍历每一次探险的记录。对于每条记录,将其中的营地名与已知的集合进行比较,如果发现新的营地(即不在集合中的营地),则将这个新营地添加到集合中,并计数新发现的营地数量。如果某次探险发现的新营地数量超过之前的最大值,则更新最大值并记录当前的探险索引。最后,返回发现新营地最多的探险索引,如果没有发现新营地则返回-1。
时间复杂度:
O(n * m)
空间复杂度:
O(n * m)
代码细节讲解
🦆
在题解中,如何处理和识别大小写不同的营地名称?
▷🦆
为什么选择使用集合(set)来存储已知的营地,而不是使用其他数据结构如列表或字典?
▷🦆
题解中提到跳过空的探险记录,空记录是如何定义的?是否包括只有'->'符号无实际营地名称的记录?
▷