Assume you work at a video streaming service and are asked to build a solution that will recommend videos to users on their home page. How would you approach this?
Given an integer array nums, return the third distinct maximum number in this array.
Example:
Input: [6,4,2,3]
Output: 3
Explanation:
The first distinct maximum is 6.
The second distinct maximum is 4.
The third distinct maximum is 3.
这道题表面上是视频首页推荐系统设计题,但题面给出的核心算法部分其实是“返回数组中第三个不同的最大值”。解题关键在于处理重复元素,因此不能只看排序后的前三个数,而要维护三个互不相同的最大值。常见做法是一次遍历数组,用三个变量分别记录第一、第二、第三大值,遇到重复值直接跳过;这样可以在 O(n) 时间、O(1) 额外空间内完成。示例 [6,4,2,3] 中,最大值依次为 6、4、3,所以答案是 3。
正文完