提交 ad7247dd 编写于 作者: 檀越@新空间's avatar 檀越@新空间 🐭

fix:最接近的三数之和

上级 d00af2af
"""
最接近的三数之和
"""
import heapq
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
"""
思路:最关键的是找出最接近的数
:param nums:
:param target:
:return:
"""
nums.sort()
ans = nums[0] + nums[1] + nums[2]
for i in range(len(nums)):
left = i + 1
right = len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if abs(target - total) < abs(target - ans):
ans = total
if total > target:
right -= 1
elif total < target:
left += 1
else:
return total
return ans
if __name__ == '__main__':
result = Solution().threeSumClosest([-1, 2, 1, -4], 1)
print(result)
"""
相交链表
"""
from typing import List, Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
"""
思路:如果存在交点,则肯定在两个链表分别遍历对方时相交
:param headA:
:param headB:
:return:
"""
if not headA or not headB:
return None
nodeA, nodeB = headA, headB
while nodeA != nodeB:
nodeA = nodeA.next if nodeA else headB
nodeB = nodeB.next if nodeB else headA
return nodeA
if __name__ == '__main__':
l1 = ListNode(4)
l1.next = ListNode(1)
l1.next.next = ListNode(8)
l1.next.next.next = ListNode(4)
l1.next.next.next.next = ListNode(5)
# l1.next.next.next.next.next = ListNode(9)
# l1.next.next.next.next.next.next = ListNode(9)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(1)
l2.next.next.next = ListNode(8)
l2.next.next.next.next = ListNode(4)
l2.next.next.next.next.next = ListNode(5)
result = Solution().getIntersectionNode(l1, l2)
print(result)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册