捉迷藏中可捕获的最大人数

Submission

运行时间: 95 ms

内存: 19.8 MB

class Solution:
    def catchMaximumAmountofPeople(self, team: List[int], dist: int) -> int:
        n = len(team)
        left = ans = 0
        for i, x in enumerate(team):
            if x == 1:
                while left < n and left <= i + dist:
                    if team[left] == 0 and i - dist <= left <= i + dist:
                        ans += 1
                        left += 1
                        break
                    left += 1
        return ans
                    

                    

Explain

The provided solution uses a greedy approach to solve the problem of capturing the maximum number of people in a game of hide and seek. The basic idea is to iterate over the array `team`, where '1' represents a seeker and '0' represents a hider. For each seeker found (i.e., when `team[i] == 1`), the algorithm tries to find the nearest hider within the distance `dist` (both before and after the seeker's position). The variable `left` is used to keep track of the position from where we start looking for a hider. The inner loop iterates from `left` to `i + dist` and checks if there is a hider within the valid distance range (`i - dist <= left <= i + dist`). If a hider is found, the counter `ans` is incremented, and the search for the next hider starts from the next position after the current `left`. This approach ensures that each hider is captured by the closest seeker, maximizing the number of captures.

时间复杂度: O(n)

空间复杂度: O(1)

class Solution:
    def catchMaximumAmountofPeople(self, team: List[int], dist: int) -> int:
        n = len(team) # Total number of people
        left = ans = 0  # Initialize pointers for the left boundary and answer
        for i, x in enumerate(team):  # Iterate over each person
            if x == 1:  # If the person is a seeker
                while left < n and left <= i + dist:  # Seek within the distance limit
                    if team[left] == 0 and i - dist <= left <= i + dist:  # Check if there's a hider in range
                        ans += 1  # Capture the hider
                        left += 1  # Move to the next potential hider
                        break
                    left += 1  # Move left pointer if no valid hider is found
        return ans  # Return the maximum number of captures

Explore

从每个搜索者的位置开始搜索可以更有效地利用贪心算法的特性,即尽可能早地做出选择以优化目标(在这里是最大化被捕获的隐藏者数量)。从搜索者的位置开始,可以立即检查附近是否有可捕获的隐藏者,这样一来一旦找到隐藏者就可以立即捕获,避免了从隐藏者角度出发可能出现的多个搜索者对一个隐藏者的重复考虑,从而实现了更高效的捕获策略。

`left`指针在算法中用于追踪当前考虑捕获的隐藏者的位置。每次当一个隐藏者被捕获时,`left`指针会向前移动到下一个位置,这保证了一旦一个隐藏者被捕获,他就不会被再次考虑,从而避免了重复计算。通过始终向前移动`left`指针,算法确保每个隐藏者只被计算一次。

当`dist`非常大时,搜索者可以捕获远距离内的任何隐藏者,这可能导致几乎所有隐藏者都被很快捕获,使算法效率极高,但也可能引起资源浪费,因为搜索者可能跨越很大的距离去捕获隐藏者。当`dist`非常小时,搜索者的捕获范围受限,这可能导致捕获的隐藏者数量减少,特别是当隐藏者和搜索者分布较为稀疏时,这种情况下算法的效果会受到较大影响。

如果搜索者和隐藏者的分布极不均匀,比如大部分搜索者集中在数组的一端而隐藏者集中在另一端,这会导致算法效率降低,因为搜索者可能需要检查较远的距离才能找到隐藏者。此外,这种分布可能导致捕获的隐藏者数量减少,因为不是所有隐藏者都在搜索者的捕获范围内。算法的总体效果和效率将受到这种不均匀分布的影响。