Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-10-04 13:15:25
※ 引述《dont (dont)》之铭言:
: 2491. Divide Players Into Teams of Equal Skill
: ## 思路
: chemistry会是最大跟最小的skill相加
: 排序后, 每次从头尾各取一
: 如果相加的和不等于chemistry就回传-1
: ## Code
: ```python
: class Solution:
: def dividePlayers(self, skill: List[int]) -> int:
: skill.sort()
: res = 0
: chemistry = skill[0] + skill[-1]
: for i in range(len(skill) // 2):
: if skill[i] + skill[~i] != chemistry:
: return -1
: res += skill[i] * skill[~i]
: return res
: ```
思路:
差不多 先头尾相加 然后遍历 有不相等的就return -1
Python Code:
class Solution:
def dividePlayers(self, skill: List[int]) -> int:
skill.sort()
start = 1
end = len(skill) - 2
tmp = skill[0] + skill[-1]
result = skill[0] * skill[-1]
while start < end:
if skill[start] + skill[end] != tmp:
return -1
result += skill[start] * skill[end]
start += 1
end -= 1
return result

Links booklink

Contact Us: admin [ a t ] ucptt.com