Leetcode习题合并K个排序链表,旋转排序数列等

合并K个排序链表

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        n=len(lists)
        if not lists:
            return 
        else:
            return self.merge(lists,0,n-1)

    def merge(self, lists, L, R):
        if L==R:
            return lists[L]
        mid=L+(R-L)//2
        l1=self.merge(lists,L, mid)
        l2=self.merge(lists,mid+1,R)
        return self.mergeTwoLists(l1,l2)

    def mergeTwoLists(self,l1,l2):
        if not l1:
            return l2
        if not l2:
            return l1
        if l1.val<l2.val:
            l1.next=self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next=self.mergeTwoLists(l1,l2.next)
            return l2

删除排序数组的重复项

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i,j=0,1
        n=len(nums)
        while j<n:
            if nums[j]==nums[i]:
                j+=1
            else:
                i+=1
                nums[i]=nums[j]
        return i+1

搜索旋转排序数列

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if not nums:
            return -1

        l=0
        r=len(nums)-1

        while l<=r:
            mid=(l+r)//2

            if nums[mid]==target:
                return mid

            if nums[0]<=nums[mid]:
                if nums[0]<=target<=nums[mid]:
                    r=mid-1
                else:
                    l=mid+1

            else:
                if nums[mid]<target<=nums[len(nums)-1]:
                    l=mid+1
                else:
                    r=mid-1

        return -1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值