3616. Number of Student Replacements 🔒
题目描述
You are given an integer array ranks
where ranks[i]
represents the rank of the ith
student arriving in order. A lower number indicates a better rank.
Initially, the first student is selected by default.
A replacement occurs when a student with a strictly better rank arrives and replaces the current selection.
Return the total number of replacements made.
Example 1:
Input: ranks = [4,1,2]
Output: 1
Explanation:
- The first student with
ranks[0] = 4
is initially selected. - The second student with
ranks[1] = 1
is better than the current selection, so a replacement occurs. - The third student has a worse rank, so no replacement occurs.
- Thus, the number of replacements is 1.
Example 2:
Input: ranks = [2,2,3]
Output: 0
Explanation:
- The first student with
ranks[0] = 2
is initially selected. - Neither of
ranks[1] = 2
orranks[2] = 3
is better than the current selection. - Thus, the number of replacements is 0.
Constraints:
1 <= ranks.length <= 105
1 <= ranks[i] <= 105
解法
方法一:模拟
我们用一个变量 \(\text{cur}\) 来记录当前选中的学生的排名。遍历数组 \(\text{ranks}\),如果遇到一个排名更好的学生(即 \(\text{ranks}[i] < \text{cur}\)),则更新 \(\text{cur}\) 并将答案加一。
遍历结束后,返回答案即可。
时间复杂度 \(O(n)\),其中 \(n\) 是学生的数量。空间复杂度 \(O(1)\)。
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 |
|