【贪心】尽量让运动员和比他大的最小的教练匹配,分别将player和trainer排序,双指针从小到达枚举即可。
class Solution {
public int matchPlayersAndTrainers(int[] players, int[] trainers) {
Arrays.sort(players);
Arrays.sort(trainers);
int m = players.length, n = trainers.length, i = 0, j = 0, ans = 0;
while (i < m && j < n) {
if (players[i] <= trainers[j]) {
ans++; i++; j++;
} else {
j++;
}
}
return ans;
}
}
class Solution {
public:
// 排序+贪心
// 10:47 3
int matchPlayersAndTrainers(vector<int>& players, vector<int>& trainers) {
sort(players.begin(), players.end());
sort(trainers.begin(), trainers.end());
int ans = 0, i = 0, j = 0;
while (i < players.size() && j < trainers.size()) {
if (players[i] <= trainers[j]) {
i++; ans++;
}
j++;
}
return ans;
}
};