Amazon OA 面试真题解析:连续子数组的最小 Watch Score

14次阅读
没有评论

Given an array watch_history of size n, that represents the web series watched by a viewer over a period of days, and two integers, series1 and series2, report the minimum watch score of a contiguous period of days in which both series1 and series2 have been viewed at least once.

If series1 and series2 are the same value, one occurrence during the period is sufficient.

The watch score of a contiguous period is the number of distinct series watched during that period.

Return the minimum watch score.

Function Description

Complete the function getMinScore in the editor below.

getMinScore has the following parameters:

  • INTEGER_ARRAY watch_history
  • INTEGER series1
  • INTEGER series2

Returns

int: the minimum watch score of a contiguous period of days in which series1 and series2 have been viewed at least once

Example

n = 5
series1 = 1
series2 = 2
watch_history = [1, 3, 2, 1, 4]

The contiguous periods of days in which series1 and series2 have been viewed at least once are:

  • [1, 3, 2] → watch score 3
  • [3, 2, 1] → watch score 3
  • [2, 1] → watch score 2
  • [1, 3, 2, 1] → watch score 3
  • [1, 3, 2, 1, 4] → watch score 4

The minimum watch score is 2.

Constraints

  • 1 <= n <= 10^5
  • 1 <= watch_history[i] <= 10^9
  • 1 <= series1, series2 <= 10^9
  • series1 and series2 are not necessarily distinct
  • There will be at least one occurrence of both series1 and series2 in watch_history

这道题的核心是滑动窗口:在数组中寻找一个连续子数组,使它同时包含 series1 和 series2,并且子数组内不同元素的数量最少,也就是 watch score 最小。做法通常是用双指针维护一个窗口,并用哈希表统计窗口内每个系列的出现次数;当窗口已经同时满足包含目标系列时,就尽量缩小左边界,同时更新当前不同元素个数。若 series1 和 series2 相同,只需要窗口中出现一次即可。因为 n 可达 10^5,这种 O(n) 的滑动窗口配合计数结构是最合适的。

正文完
 0