import java.util.HashSet;
import java.util.Set;
public static boolean canTwoMoviesFillFlight(int[] movieLengths, int flightLength) {
// movie lengths we've seen so far
Set<Integer> movieLengthsSeen = new HashSet<>();
for (int firstMovieLength : movieLengths) {
int matchingSecondMovieLength = flightLength - firstMovieLength;
if (movieLengthsSeen.contains(matchingSecondMovieLength)) {
return true;
}
movieLengthsSeen.add(firstMovieLength);
}
// we never found a match, so return false
return false;
}
HashSet如何已经具有来自movieLengths的所有值?
此问题询问要找到两部电影的总和为给定的持续时间。
您可以通过存储此特定电影的补编来使用哈希集。假设您在第一次迭代中有一部电影(60分钟),然后计算其补编来填充整个飞行时间(100分钟)。首先,该集合为空,因此找不到该值,需要将持续时间插入到集合中。在第二个迭代中,您将拥有40分钟的电影,因此,如果其中包含(100-40 = 60)分钟的电影,您将搜索该集合,并且您会发现插入了第一部电影。因此,您将返回true。
您的HashSet
是创建后为空:
Set<Integer> movieLengthsSeen = new HashSet<>();
但是,下一组是循环传递到方法中的一组值。我添加了评论以供澄清:
//movieLenghts is passed in
for (int firstMovieLength : movieLengths) {
//create value from 2 passed in params
int matchingSecondMovieLength = flightLength - firstMovieLength;
//Here it checks to see if the value has been added to the hash,
//if so, return true (won't happen on the first pass).
//Otherwise continue with the algorithm.
if (movieLengthsSeen.contains(matchingSecondMovieLength)) {
return true;
}
//If the hash doesn't have the value, which it won't on the first pass
//and possible subsequent passes, it will add the value and repeat
movieLengthsSeen.add(firstMovieLength);
}
TLDR;HashSet
是为空。它会在for循环运行时填充。