题解 | #农场牛类别匹配#
农场牛类别匹配
https://www.nowcoder.com/practice/270db1e1d65b4366a49a517ec7822912
考察的知识点:哈希;
解答方法分析:
- 检查列表长度是否为奇数,如果是,则无法两两匹配,直接返回 -1。
- 对列表进行排序,将列表中的元素按升序排列。
- 使用双指针的方法来查找配对的元素。初始化两个指针
left和right分别指向列表的开头和末尾。 - 在一个循环中,函数检查当前指向的两个元素的和是否等于目标和。如果是,就将配对的个数
cnt加1,并将两个指针向中间移动一。如果和小于目标和,就将左指针向后移一步。如果和大于目标和,就将右指针向前移动一步。 - 返回配对的数
cnt。
所用编程语言:C++;
完整编程代码:↓
class Solution {
public:
int countMatchingPairs(vector<int>& breeds, int target_sum) {
int n = breeds.size();
if (n % 2 == 1) {
return -1;
}
sort(breeds.begin(), breeds.end());
int cnt = 0;
int left = 0, right = n - 1;
while (left < right) {
if (breeds[left] + breeds[right] == target_sum) {
cnt += 1;
left += 1;
right -= 1;
} else if (breeds[left] + breeds[right] < target_sum) {
left += 1;
} else {
right -= 1;
}
}
return cnt;
}
};