游戏排名第三大的分数

76 阅读1分钟

Problem Explanation

The task is to find the third distinct largest score from a list of scores. If there are less than three distinct scores, the function should return the highest score.

Solution Approach

  1. Input Processing:

    • The function receives an integer n, which indicates the number of scores, and a list nums containing the scores.
  2. Removing Duplicates:

    • We need to ensure that we only consider unique scores. This is efficiently achieved by converting the list to a set.
  3. Sorting:

    • Once we have the unique scores, we sort them in ascending order. This allows us to easily access the largest scores.
  4. Extracting the Result:

    • If there are three or more unique scores, the third largest is located at the index -3 of the sorted list.
    • If there are less than three unique scores, we return the largest score, which is at the index -1.

Implementation

Here’s the implementation you provided, which follows the outlined approach:

def solution(n: int, nums: list) -> int:
    # 去重并排序
    unique_scores = sorted(set(nums))
    
    # 判断不同分数的数量
    if len(unique_scores) >= 3:
        return unique_scores[-3]  # 返回第三大的分数
    else:
        return unique_scores[-1]  # 返回最大的分数
 
if __name__ == '__main__':
    print(solution(3, [3, 2, 1]) == 1)  # Expecting: 1
    print(solution(2, [1, 2]) == 2)      # Expecting: 2
    print(solution(4, [2, 2, 3, 1]) == 1)  # Expecting: 1

Test Cases Explained

  1. Test Case 1:

    • Input: solution(3, [3, 2, 1])
    • Unique scores: [1, 2, 3] (sorted)
    • Third largest: 1
    • Output: 1
  2. Test Case 2:

    • Input: solution(2, [1, 2])
    • Unique scores: [1, 2] (sorted)
    • Less than three distinct scores, so return the largest: 2
    • Output: 2
  3. Test Case 3:

    • Input: solution(4, [2, 2, 3, 1])
    • Unique scores: [1, 2, 3] (sorted)
    • Third largest: 1
    • Output: 1

Conclusion

The provided function correctly identifies the third largest score or the maximum score when fewer than three distinct scores exist, fulfilling the problem requirements efficiently.