【Leetcode】EASY题解....ing python

1. 两数之和[medium]

解题思路

保持每个对应位数的进制carry,对应位置进行运算就行,循环终止条件是l1 or l2 or carry;

代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        temp = p = ListNode(None)
        carry = 0 
        sum = 0
        while l1 or l2 or carry:
            sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
            p.next = ListNode(sum % 10)
            p = p.next
            carry = sum // 10            
            l1 = l1.next if l1 else None           
            l2 = l2.next if l2 else None
        return temp.next    


7. 整数反转[easy]

解题思路

整数翻转转化为字符串翻转,之后再将其转为int类型,判断原始数值和翻转后的数组是否再给定的范围内即可

代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x > 2**31 - 1 or x < -2**31:
            return 0
        if x < 0 and x >= -2**31:
            x = abs(x)
            x = str(x)
            s = x[::-1]
            s = -int(s)
            if s < -2**31:
                return 0
            return s
        elif x >= 0 and x <= 2**31 - 1:
            x = str(x)
            s = x[::-1]
            s = int(s)
            if s > 2**31 - 1:
                return 0
            else:
                return s


8. 字符串转换整数 (atoi)[M]

解题思路

此处撰写解题思路

代码

class Solution(object):
    def myAtoi(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = int(*re.findall('^[\+\-]?\d+', s.lstrip()))
        if result < -2**31:
            result = -2**31
        elif result > 2**31 - 1:
            result = 2**31 - 1

    
        return result
        #return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)

9.回文数

解题思路

将整数变为字符串,如果整数为负数,直接判断不是回文,非负数则将字符串反转,比较反转后的int值和原值是否相等;

代码

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        # 将整数变为字符串
        if x >=0:
            s = str(x)
            # 将字符串反转
            s = s[::-1]
            if int(s) == int(x):
                return True
            else:
                return False
        else:
            return False


12. 整数转罗马数字

解题思路

定义一个列表数组,遍历数组,退出条件是nums = 0
将list 转为str()

  1. result.toString()
  2. result = ‘’.join(result)

代码

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        result = []
    # 定义一个字典
        # dict = {'I':1, 'IV':4, 'V':5, 'IX':10, 'X':10, 'XL':40, 'L':50, 'XC':90, 'C':100, 'CD':400, 'D':500, 'CM':900, 'M':1000}
        dict = [
            [1000, 'M'],
            [900, 'CM'],
            [500, 'D'],
            [400, 'CD'],
            [100, 'C'],
            [90, 'XC'],
            [50, 'L'],
            [40, 'XL'],
            [10, 'X'],
            [9, 'IX'],
            [5, 'V'],
            [4, 'IV'],
            [1, 'I'],
        ]


        for value, key in dict:
            while(num >= value):
                result.append(key)
                num -= value
            if num == 0:
                break
                
        result = ''.join(result)
        return result

15. 三数之和

解题思路

双指针+for循环
对 i for 循环,定义j,k 指针,遍历,找到符合条件的列表
对于不符合条件有几种

  1. nums 长度小于3 并且最小值>0
  2. nums[j] == nums[j+1] or nums[k] == nums[k-1]
  3. nums[i] + nums[j] + nums[k] > 0 or nums[i] + nums[j] + nums[k] < 0

代码

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []
        nums.sort()

        for i in range(len(nums)):
            j = i + 1
            k = len(nums) - 1
            if nums[i]>0 or len(nums)<3:
                return result
            if i > 0 and nums[i] == nums[i-1]:
                continue
            while(j < k):
                if nums[i] + nums[j] + nums[k] == 0:
                    result.append([nums[i],nums[j],nums[k]])
                    while(j < k and nums[j] == nums[j+1]):
                        j = j + 1
                    while(j < k and nums[k] == nums[k-1]):
                        k = k - 1
                    j += 1
                    k -= 1

                elif nums[i] + nums[j] + nums[k] < 0:
                    j += 1
                elif nums[i] + nums[j] + nums[k] > 0:
                    k -= 1
        return result
  

20. 有效的括号[easy]

解题思路

判断如果长度为奇数,直接返回false;
直接将配对括号去掉

代码

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        # 用栈求解
        if len(s)%2 != 0:
            return False
        while '()' in s or '[]' in s or '{}' in s:
            s = s.replace('[]','').replace('()','').replace('{}','')
        return True if s == '' else False

21. 合并两个有序链表

解题思路

两个指针,一个头指针,一个移动指针,变换的都是移动指针,最后返回头指针的next;
cur.next = l1 if l1 is not None else l2

代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        cur = ListNode()
        temp = cur # 保存头指针,移动的是cur指针
        while l1 and l2:
            if l1.val <= l2.val:
                cur.next = l1
                l1 = l1.next
            elif l1.val > l2.val:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        if l1 is not None:
            cur.next = l1
        elif l2 is not None:
            cur.next = l2
        return temp.next
            

27. 移除元素[Easy]

解题思路

计算除去val之后元素的个数,之后对nums进行排序
image.png

代码

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        count = nums.count(val)
        l = len(nums) - count
        j = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[j] = nums[i]
                j += 1
        return l

23. 合并K个升序链表

思路

  1. 将list每个list提取出来合并排序,
  2. 重新将list直接串成链表

代码




# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        result = []
        for i in lists:
            while i: 
                result.append(i.val)
                i = i.next
        first = cur = ListNode(-1)
        result.sort()
        for j in result:
            cur.next = ListNode(j)
            cur = cur.next
        return first.next



26. 删除有序数组中的重复项[easy]

题目

给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。

不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/

解题思路

如果后一个元素与前一个元素不相等的话,按顺序将元素zai nums数组中进行组合

代码

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        j = 1
        for i in range(1,len(nums)):
            if nums[i] != nums[i-1]:
                nums[j] = nums[i]
                j+=1
        return j
            

53. 最大子序和

解题思路

  1. nums 长度为1 直接返回
  2. 先将max置为最小值,如果每一次加上下一个数sum值能变大,变换max值

代码

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        ans = []
        max = -10e5
        if len(nums) == 1:
            return nums[0]


        sum = 0
        for i in range(len(nums)):
            
            sum = sum + nums[i]
            if sum >= max:
                max = sum 
            if sum <=0:
                sum = 0
        return max



58. 最后一个单词的长度

解题思路

代码

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s.strip(" ")
        l = s.replace(",", " ")
        ans = l.split(" ")
        result = ans[-1]
        count = 0
        count = len(result)
        return count

67. 二进制求和

解题思路

  1. 将二进制转为十进制进行运算
  2. 将结果转为二进制(bin())
  3. 去除表示进制的前两个字符
    image.png

代码

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        # 求解二进制,转为十进制,再转为二进制
        t1 = int(a, 2)
        t2 = int(b, 2)
        sum = t1 + t2
        ans = bin(sum)
        return ans[2:] # 去除进制前缀

88. 合并两个有序数组

题目

给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。

请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。

注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。

解题思路

  1. 直接将 nums2 接在 nums1 后面
  2. 对 nums1 进行排序

代码

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        j = 0
        for i in range(m,m+n):
            nums1[i] = nums2[j]
            j = j + 1
        nums1.sort()
        return nums1

110. 平衡二叉树

题目

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

解题思路

  1. 求出左右子树的最大高度
  2. 判断树是否为空
  3. 判断是否左右子树都为平衡子树

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isBalanced(self, root):
        def height(root):
            if not root:
                return 0
            return max(height(root.left), height(root.right)) + 1

        if not root:
            return True
        return abs(height(root.left) - height(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)




        

101. 对称二叉树

题目

给定一个二叉树,检查它是否是镜像对称的

解题思路

  1. 思考
  2. 利用递归
  3. 给两个根节点,从对称的方向向下递归,判断对称节点是否对称
  4. 返回相应的bool

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:

        return self.isequeal(root,root)

    def isequeal(self , p: TreeNode, q:TreeNode)->bool:
        if (p is None and q is None):
            return True
        if (p is None or q is None):
            return False
        if (p.val == q.val): # 只有对称才进行下一步递归
            return self.isequeal(p.left, q.right) and self.isequeal(p.right, q.left)

        else: # 不对称直接return 
            return False

111. 二叉树的最小深度

题目

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

解题思路

  1. 递归,确定递归结束条件:数为空时:return 0 else 1
  2. 判断左右子树
  3. 全部非空由之前深度加上当前1
  4. 左右子树部分非空

代码


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """

        if root is None: # 树为空
            return 0 
        if root.left and root.right: # 左右子树都非空
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
        if root.left: # 左子树非空
            return 1 + self.minDepth(root.left)
        if root.right: # 右子树非空
            return 1 + self.minDepth(root.right)
        else:
            return 1

剑指Offer

剑指 Offer 03. 数组中重复的数字

解题思路

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

示例 1:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3

排序比较

代码

from collections import Counter
class Solution(object):
    def findRepeatNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        for i in range(len(nums)):
            if nums[i]==nums[i+1]:
                return nums[i]
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jucway

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值