LeetCode 2410. 运动员和训练师的最大匹配数

2410. 运动员和训练师的最大匹配数

 

LeetCode 2410. 运动员和训练师的最大匹配数_第1张图片

【贪心】尽量让运动员和比他大的最小的教练匹配,分别将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& players, vector& 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;
    }
};

 

 

 

你可能感兴趣的:(LeetCode,贪心)