First, sort both players and trainers in ascending order and then
run a two pointers algorithm that iterate through both players and trainers,
incrementing the number of matchings if there exists a trainer to train the current player.
code
class Solution {
public:
int matchPlayersAndTrainers(vector<int>& players, vector<int>& trainers) {
sort(players.begin(), players.end());
sort(trainers.begin(), trainers.end());
int playerIndex = 0;
int trainerIndex = 0;
int ans = 0;
while (playerIndex < players.size() && trainerIndex < trainers.size()) {
while(trainerIndex < trainers.size() && trainers[trainerIndex] < players[playerIndex]) {
++trainerIndex;
}
if (trainerIndex < trainers.size() && players[playerIndex] <= trainers[trainerIndex]) {
++ans;
++playerIndex;
++trainerIndex;
}
}
return ans;
}
};
complexity
- Time:
O(n log(n) + m log(m))wherenis the number of elements insideplayers, andmis the number of elements insidetrainers- Space:
O(1)
time taken
- 5 minutes and 34 seconds