python-leetcode刷题记录(一)


一、1. 两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict={}
        for i in range(len(nums)):
            if target-nums[i] not in dict:
                dict[nums[i]]=i
            else :
                return [dict[target-nums[i]],i]

二、有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

 match={']':'[',')':'(','}':'{'}
        li=[]
        if len(s)%2!=0:
            return False
        for ch in s:
            
            if ch in match and li:
                
                if match[ch] == li[-1]:
                    li.pop()
                else:
                    return False
            else:
                li.append(ch)
        
        return not li

三、合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

方法1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        new_list=None
        if l1==None or l2==None:
            return l1 if l1 is not None else l2
        elif l1.val<=l2.val:
            new_list=l1
            new_list.next=self.mergeTwoLists(l1.next,l2)
        else:
            new_list=l2
            new_list.next=self.mergeTwoLists(l1,l2.next)
        return new_list

方法2

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        head=ListNode(-1)
        head_list=head
        while l1 and l2:
            if l1.val<=l2.val:
                head_list.next=l1
                l1=l1.next
            else:
                head_list.next=l2
                l2=l2.next
            head_list=head_list.next
        head_list.next=l1 if l1 is not None else l2
        return head.next
        

四、搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left = 0
        right = len(nums)
        while left<right:
            mid = (left+right)//2
            if nums[mid]>=target:
                right = mid
            else:
                left = mid + 1
        return left 

五、 删除有序数组中的重复项

给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

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

六、 搜索二维矩阵

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

写法一

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        h=len(matrix)-1
        w=0
        while h>=0 and w<len(matrix[0]):
            if matrix[h][w]<target:
                w+=1
            elif matrix[h][w]>target:
                h-=1
            else:
                return True
        else:
            return False

#写法2

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        h=len(matrix)#行数
        w=len(matrix[0])#列数
        if h==0 or w==0:#[] or [[],[]]
            return False
        left=0
        right=h*w-1
        while left <= right:
            mid=(left+right)//2#中间值的下标
            i=mid//w#所在行
            j=mid%w#所在列
            if matrix[i][j]==target:
                return True
            elif matrix[i][j]<target:
                left=mid+1
            else:
                right=mid-1
        else:
            return False

七、 删除排序链表中的重复元素

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return head
        cur=head
        while cur.next:  
            if cur.val==cur.next.val: 
                cur.next=cur.next.next
            else:
                cur=cur.next
        return head

八、 只出现一次的数字

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        r=0
        for i in nums:
            r^=i
        return r

九、 两数之和 II - 输入有序数组

给定一个已按照 非递减顺序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。
你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。

写法1

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        dict={}
        for i,x in enumerate(numbers):
            if target-x in dict:
                return [dict[target-x]+1,i+1]
            else:
                dict[x]=i

写法2

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        left=0
        right=len(numbers)-1
        while left<right:
            if numbers[left]+numbers[right]==target:
                return [left+1,right+1]
            elif numbers[left]+numbers[right]>target:
                right-=1
            else:
                left+=1

十、 移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

写法1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        
        if  head==None:
            return head
        
        head.next=self.removeElements(head.next,val)
        return head if head.val!=val else head.next

写法2

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        dummy = ListNode()
        dummy.next = head
        head = dummy
        while head.next is not None:
            if head.next.val == val:
                head.next = head.next.next
            else:
                head = head.next
        return dummy.next

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值