Leetcode 3238. Find the Number of Winning Players
In a game, each player has a unique skill level represented by an integer. You are given a list of unique integers skills
where skills[i]
is the skill level of the i-th
player. There is a concept of winning and losing players. A player i is considered a winner if there are exactly k
players with a skill level less than skills[i]
. You need to write a function to find the number of winning players.
The function signature should be:
int findWinningPlayers(vector<int>& skills, int k);
skills
: A list of unique integers representing the skill levels of the players. [skills[i]]
(1 ≤ skills.length
≤ 1000, -10^9
≤ skills[i]
≤ 10^9
).k
: An integer specifying the required count of players with lesser skill levels. (0 ≤ k < skills.length)
.vector<int> skills = {3, 5, 7, 2, 8};
int k = 2;
// Output: 2
// Explanation: The players with skills 5 and 7 are winning players since there are exactly 2 players with skill levels less than theirs.
0
.To solve the problem:
skills
List: First, sort the list of skills.i
matches the count k
. If so, increment the counter for winning players.skills
list. Sorting simplifies the process of determining the number of players with lower skill levels.k
. Count the players whose situation matches the condition.Below is the implementation in C++:
#include <vector>
#include <algorithm>
using namespace std;
int findWinningPlayers(vector<int>& skills, int k) {
// Step 1: Sort the skills array
sort(skills.begin(), skills.end());
int count = 0;
// Step 2: Iterate through the sorted array and count the winners
for (int i = 0; i < skills.size(); ++i) {
if (i == k) {
count++;
}
}
return count;
}
Thus, the overall time complexity is (O(n \log n)) due to the sorting step. The space complexity is (O(1)) if we don’t consider the input array itself.
This should efficiently handle the constraints given in the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?