题解 | #农场牛类别匹配#
农场牛类别匹配
https://www.nowcoder.com/practice/270db1e1d65b4366a49a517ec7822912
- 题目考察的知识点 : 数组,双指针
- 题目解答方法的文字分析:
- 将输入数组 breeds 进行排序,然后使用双指针 left 和 right 指向排序后的数组中的头尾元素。若两个指针所指元素之和等于目标值,则可以将它们匹配成一组;否则如果之和小于目标值,则将 left 向右移动;如果之和大于目标值,则将 right 向左移动。直到 left >= right 时停止循环,返回匹配成功的组数
- 本题解析所用的编程语言: Python
- 完整且正确的编程代码
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param breeds int整型一维数组
# @param target_sum int整型
# @return int整型
#
class Solution:
def countMatchingPairs(self, breeds: List[int], target_sum: int) -> int:
n = len(breeds)
if n % 2 == 1: # 如果数组长度为奇数,则无法两两匹配
return -1
breeds.sort() # 排序
cnt = 0
left, right = 0, n - 1
while left < right:
if breeds[left] + breeds[right] == target_sum:
cnt += 1
left += 1
right -= 1
elif breeds[left] + breeds[right] < target_sum:
left += 1
else:
right -= 1
return cnt
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路