欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 编程语言 > >内容正文

python

【leetcode】easy题解....ing python -凯发k8官方网

发布时间:2025/1/21 18 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 【leetcode】easy题解....ing python 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

    • 1. 两数之和[medium]
      • 解题思路
      • 代码
    • 7. 整数反转[easy]
      • 解题思路
      • 代码
    • 8. 字符串转换整数 (atoi)[m]
      • 解题思路
      • 代码
    • 9.回文数
      • 解题思路
      • 代码
    • 12. 整数转罗马数字
      • 解题思路
      • 代码
    • 15. 三数之和
      • 解题思路
      • 代码
    • 20. 有效的括号[easy]
      • 解题思路
      • 代码
    • 21. 合并两个有序链表
      • 解题思路
      • 代码
    • 27. 移除元素[easy]
      • 解题思路
      • 代码
    • 23. 合并k个升序链表
      • 思路
      • 代码
    • 26. 删除有序数组中的重复项[easy]
      • 题目
      • 解题思路
      • 代码
    • 53. 最大子序和
      • 解题思路
      • 代码
    • 58. 最后一个单词的长度
      • 解题思路
      • 代码
    • 67. 二进制求和
      • 解题思路
      • 代码
    • 88. 合并两个有序数组
      • 题目
      • 解题思路
      • 代码
    • 110. 平衡二叉树
      • 题目
      • 解题思路
      • 代码
    • 101. 对称二叉树
      • 题目
      • 解题思路
      • 代码
    • 111. 二叉树的最小深度
      • 题目
      • 解题思路
      • 代码
  • 剑指offer
      • 剑指 offer 03. 数组中重复的数字
      • 解题思路
      • 代码

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 = 0while l1 or l2 or carry:sum = (l1.val if l1 else 0) (l2.val if l2 else 0) carryp.next = listnode(sum % 10)p = p.nextcarry = sum // 10 l1 = l1.next if l1 else none l2 = l2.next if l2 else nonereturn 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 0if x < 0 and x >= -2**31:x = abs(x)x = str(x)s = x[::-1]s = -int(s)if s < -2**31:return 0return selif x >= 0 and x <= 2**31 - 1:x = str(x)s = x[::-1]s = int(s)if s > 2**31 - 1:return 0else: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**31elif result > 2**31 - 1:result = 2**31 - 1return 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 trueelse:return falseelse:return false

12. 整数转罗马数字

解题思路

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

  • result.tostring()
  • 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 -= valueif num == 0:breakresult = ''.join(result)return result

    15. 三数之和

    解题思路

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

  • nums 长度小于3 并且最小值>0
  • nums[j] == nums[j 1] or nums[k] == nums[k-1]
  • 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 1k = len(nums) - 1if nums[i]>0 or len(nums)<3:return resultif i > 0 and nums[i] == nums[i-1]:continuewhile(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[j1]):j = j 1while(j < k and nums[k] == nums[k-1]):k = k - 1j = 1k -= 1elif nums[i] nums[j] nums[k] < 0:j = 1elif nums[i] nums[j] nums[k] > 0:k -= 1return result

    20. 有效的括号[easy]

    解题思路

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

    代码

    class solution(object):def isvalid(self, s):""":type s: str:rtype: bool"""# 用栈求解if len(s)%2 != 0:return falsewhile '()' 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 = l1l1 = l1.nextelif l1.val > l2.val:cur.next = l2l2 = l2.nextcur = cur.nextif l1 is not none:cur.next = l1elif l2 is not none:cur.next = l2return temp.next

    27. 移除元素[easy]

    解题思路

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

    代码

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

    23. 合并k个升序链表

    思路

  • 将list每个list提取出来合并排序,
  • 重新将list直接串成链表
  • 代码

    # definition for singly-linked list. # class listnode(object): # def __init__(self, val=0, next=none): # self.val = val # self.next = nextclass 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.nextfirst = cur = listnode(-1)result.sort()for j in result:cur.next = listnode(j)cur = cur.nextreturn 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 = 1for i in range(1,len(nums)):if nums[i] != nums[i-1]:nums[j] = nums[i]j =1return j

    53. 最大子序和

    解题思路

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

    class solution(object):def maxsubarray(self, nums):""":type nums: list[int]:rtype: int"""count = 0ans = []max = -10e5if len(nums) == 1:return nums[0]sum = 0for i in range(len(nums)):sum = sum nums[i]if sum >= max:max = sum if sum <=0:sum = 0return 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 = 0count = len(result)return count

    67. 二进制求和

    解题思路

  • 将二进制转为十进制进行运算
  • 将结果转为二进制(bin())
  • 去除表示进制的前两个字符
  • 代码

    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 t2ans = bin(sum)return ans[2:] # 去除进制前缀

    88. 合并两个有序数组

    题目

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

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

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

    解题思路

  • 直接将 nums2 接在 nums1 后面
  • 对 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 = 0for i in range(m,mn):nums1[i] = nums2[j]j = j 1nums1.sort()return nums1

    110. 平衡二叉树

    题目

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

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

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

    解题思路

  • 求出左右子树的最大高度
  • 判断树是否为空
  • 判断是否左右子树都为平衡子树
  • 代码

    # 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 0return max(height(root.left), height(root.right)) 1if not root:return truereturn abs(height(root.left) - height(root.right)) <= 1 and self.isbalanced(root.left) and self.isbalanced(root.right)

    101. 对称二叉树

    题目

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

    解题思路

  • 思考
  • 利用递归
  • 给两个根节点,从对称的方向向下递归,判断对称节点是否对称
  • 返回相应的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 trueif (p is none or q is none):return falseif (p.val == q.val): # 只有对称才进行下一步递归return self.isequeal(p.left, q.right) and self.isequeal(p.right, q.left)else: # 不对称直接return return false

    111. 二叉树的最小深度

    题目

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

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

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

    解题思路

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

    # 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 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[i1]:return nums[i]

    总结

    以上是凯发k8官方网为你收集整理的【leetcode】easy题解....ing python的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

    • 上一篇:
    • 下一篇:
    网站地图