【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.next7. 整數反轉[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 s8. 字符串轉換整數 (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 False12. 整數轉羅馬數字
解題思路
定義一個列表數組,遍歷數組,退出條件是nums = 0
將list 轉為str()
代碼
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 result15. 三數之和
解題思路
雙指針+for循環
對 i for 循環,定義j,k 指針,遍歷,找到符合條件的列表
對于不符合條件有幾種
代碼
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 result20. 有效的括號[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 False21. 合并兩個有序鏈表
解題思路
兩個指針,一個頭指針,一個移動指針,變換的都是移動指針,最后返回頭指針的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.next27. 移除元素[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 l23. 合并K個升序鏈表
思路
代碼
# 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.next26. 刪除有序數組中的重復項[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 j53. 最大子序和
解題思路
代碼
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 max58. 最后一個單詞的長度
解題思路
代碼
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 count67. 二進制求和
解題思路
代碼
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 。
解題思路
代碼
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 nums1110. 平衡二叉樹
題目
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義為:
一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 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. 對稱二叉樹
題目
給定一個二叉樹,檢查它是否是鏡像對稱的
解題思路
代碼
# 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 False111. 二叉樹的最小深度
題目
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明:葉子節點是指沒有子節點的節點。
解題思路
代碼
# 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]總結
以上是生活随笔為你收集整理的【Leetcode】EASY题解....ing python的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Pycharm】专业版连接xshell
- 下一篇: [pytorch ] (a) must