有人可以在 Java 中解释这个 HashSet 问题吗?

Can someone please explain this HashSet question in Java?

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) 分钟的电影,您将搜索该集合,并且您会发现您插入了第一部。所以,你会 return true.

您的HashSet在创建时是空的:

Set<Integer> movieLengthsSeen = new HashSet<>();

但是,下一步是循环遍历传递给该方法的一组值。我添加了评论以进行澄清:

//movieLengths 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 because
        //the hash set is empty).
        //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 循环的运行而填充。

当您遍历增强的 for 循环时,每个 firstMovieLength 都会在末尾添加到哈希集。因此,当您进入第二次迭代时,前面的 firstMovieLength 存在,而在第三次迭代中,前面两个是哈希集的元素,依此类推。