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
-
Input Processing:
- The function receives an integer
n, which indicates the number of scores, and a listnumscontaining the scores.
- The function receives an integer
-
Removing Duplicates:
- We need to ensure that we only consider unique scores. This is efficiently achieved by converting the list to a set.
-
Sorting:
- Once we have the unique scores, we sort them in ascending order. This allows us to easily access the largest scores.
-
Extracting the Result:
- If there are three or more unique scores, the third largest is located at the index
-3of the sorted list. - If there are less than three unique scores, we return the largest score, which is at the index
-1.
- If there are three or more unique scores, the third largest is located at the index
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
-
Test Case 1:
- Input:
solution(3, [3, 2, 1]) - Unique scores:
[1, 2, 3](sorted) - Third largest:
1 - Output:
1
- Input:
-
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
- Input:
-
Test Case 3:
- Input:
solution(4, [2, 2, 3, 1]) - Unique scores:
[1, 2, 3](sorted) - Third largest:
1 - Output:
1
- Input:
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.