23、合并K个升序链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
import heapq
dummy = ListNode(0)
p = dummy
head = []
for i in range(len(lists)):
if lists[i] :
heapq.heappush(head, (lists[i].val, i))
lists[i] = lists[i].next
while head:
val, idx = heapq.heappop(head)
p.next = ListNode(val)
p = p.next
if lists[idx]:
heapq.heappush(head, (lists[idx].val, idx))
lists[idx] = lists[idx].next
return dummy.next
24、删除排序数组中的重复项
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
lenth = len(nums)-1
if lenth > 0:
for i in range(lenth):
if nums[lenth-i] == nums[lenth-i-1]:
del nums[lenth-i-1]
return len(nums)
33、搜索旋转排序数组
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums) == 0:
return -1
l = 0
r = len(nums) - 1
while l < r:
mid = l + (r - l) // 2
if nums[mid] < nums[r]: # [mid, r]有序
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid
else: # [l, mid]有序
if nums[l] <= target <= nums[mid]:
r = mid
else:
l = mid + 1
return -1 if nums[l] != target else l