【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[j+1]):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,m+n):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
剑指 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]
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
