两数相加
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1:ListNode, l2:ListNode)->ListNode :
if not l1:
return l2
if not l2:
return l1
carry = 0
result = l2
tail = l2
while l1 or l2:
sum = (l1.val if l1 else 0) + l2.val + carry
l2.val = sum % 10
carry = sum // 10
if l1:
l1 = l1.next
if not l2.next:
tail = l2
l2.next = l1
l2 = l1
l1 = None
else:
l2 = l2.next
if carry:
tail.next = ListNode(1)
return result
寻找两个正序数组的中位数
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
def findKthElement(arr1,arr2,k):
len1,len2 = len(arr1),len(arr2)
if len1 > len2:
return findKthElement(arr2,arr1,k)
if not arr1:
return arr2[k-1]
if k == 1:
return min(arr1[0],arr2[0])
i,j = min(k//2,len1)-1,min(k//2,len2)-1
if arr1[i] > arr2[j]:
return findKthElement(arr1,arr2[j+1:],k-j-1)
else:
return findKthElement(arr1[i+1:],arr2,k-i-1)
l1,l2 = len(nums1),len(nums2)
left,right = (l1+l2+1)//2,(l1+l2+2)//2
return (findKthElement(nums1,nums2,left)+findKthElement(nums1,nums2,right))/2
最长回文子串
class Solution:
def longestPalindrome(self, s: str) -> str:
for j in range(len(s), -1, -1):
for i in range(len(s)-j, -1, -1):
if (s[i:i+j]) == s[i:i+j][::-1]:
return s[i:i+j][::-1]