系列文章目录
记录一下自己的学习过程
文章目录
基础知识
链表
节点定义:
class Node:
def __init__(self,data = None, next = None):
self.data = data
self.next = next
节点创建:
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
链表两数相加
# 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,carry=0):
if l1 is None and l2 is None:
return ListNode(carry) if carry else None
if l1 is None:
l1,l2=l2,l1
carry+=l1.val+(l2.val if l2 else 0)
if carry>=10:
l1.val=carry-10
carry=1 # 进一位
else:
l1.val=carry
carry=0
l1.next=self.addTwoNumbers(l1.next,l2.next if l2 else None,carry)
return l1
合并两个有序链表 12.7
采用的是递归
# 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, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
if list1 is None:
return list2
elif list2 is None:
return list1
elif list1.val<list2.val:
list1.next=self.mergeTwoLists(list1.next, list2)
return list1
else:
list2.next=self.mergeTwoLists(list1, list2.next)
return list2
回文 11.16
思路:把数倒过来相加和原来的进行比较。
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
num = x
cur = 0
if x >= 10:
while (num != 0):
cur = cur * 10 + num % 10
num = num / 10
return cur == x
elif x >= 0 and x < 10:
return True
else:
return False
罗马数字转换 11.16
思路一:直接暴力求解,先算出单个罗马数字对应的值,然后减去有数字组合的数值
def index_num(index):
if index=='I':
return 1
if index=='V':
return 5
if index=='X':
return 10
if index=='L':
return 50
if index=='C':
return 100
if index=='D':
return 500
if index =='M':
return 1000
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
result=0
i=0
num=s
while(i<len(num)):
result=result+index_num(num[i])
i+=1
if 'XL' in num:
result=result-20
if 'XC' in num:
result=result-20
if 'IV' in num:
result=result-2
if 'IX' in num:
result=result-2
if 'CD' in num:
result=result-200
if 'CM' in num:
result=result-200
return result
思路二:直接用哈希表存储
class Solution:
def romanToInt(self, s: str) -> int:
d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}
return sum(d.get(s[max(i-1, 0):i+1], d[n]) for i, n in enumerate(s))
作者:⚗ Knife丶👆👆👆
链接:https://leetcode.cn/problems/roman-to-integer/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
最长公共前缀 11.16
思路1:暴力求解,将第一个字符作为基准,如果后面的字符没有该前缀或长度大于该前缀,则跳过。
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result = ''
index = 0
str1 = strs[0]
if len(strs) == 1:
return str1
for j in range(1, len(str1)+1):
for k in range(1, len(strs)):
if str1[0:j] != strs[k][0:j]:
index = 0
break
elif j > len(strs[k]):
index = 0
break
else:
index = 1
if index == 1 and len(result) <= len(str1[0:j]):
result = str1[0:j]
return result
思路2:取每一个字母的同一位置字母,看是否相同
set():创建一个无序不重复元素的集合 ,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。其返回值为一个新的集合对象。
队列
滑动窗口思想:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
len_result=0
result=[]
for i in s:
if i not in result:
result.append(i)
else:
while i in result:
result=result[1:len(result)]
result.append(i)
if len_result<len(result):
len_result=len(result)
return len_result
栈 12.7
class Solution(object):
def isValid(self, s):
dic = {'{': '}', '[': ']', '(': ')','1':'1'}
stack = ['1']
for c in s:
if c in dic:
stack.append(c)
elif dic[stack.pop()] != c:
return False
return len(stack) == 1
双指针 12.7
删除有序数组中的重复项
- 暴力求解:直接定义一个result列表判断是否重复项
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result=[]
index=0
for i in nums:
if i not in result:
result.append(i)
nums[index]=i
index=index+1
return index
2 双指针
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
right=1
left=1
while(right<=len(nums)-1):
if nums[right]!=nums[right-1]:
nums[left]=nums[right]
left=left+1
right=right+1
return left
最后一个单词长度 12.7
想法:从后往前遍历就行
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
result=0
for i in range(len(s)-1,-1,-1):
if s[i]==' ' and result!=0:
return result
elif s[i]!=' ':
result=result+1
return result
加一 12.7
暴力求解了一下
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits_len = len(digits)
digits[digits_len-1] = digits[digits_len-1] + 1
for i in range(digits_len - 1, -1, -1):
if digits[i] == 10:
if i == 0:
digits.append(0)
digits[i] = 1
return digits
digits[i] = 0
i = i - 1
digits[i] = digits[i] + 1
return digits
整数反转 12.7
思路一:递归
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
result= self.reverse_1(x)
if abs(result)>2**31-1:
return 0
else:
return result
def reverse_1(self, x):
for i in range(10):
if abs(x) / 10 ** i < 10:
all = 10 ** i
break
if abs(x) < 10:
return x
if x < 0:
return x % -10*all - self.reverse_1(int(abs(x) /10))
else:
return x % 10*all + self.reverse_1(int(x / 10))
二叉树的中序遍历 12.10
思路:递归
# 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 inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result=[]
result=self.zhongxu(root,result)
return result
def zhongxu(self,root,result):
if root==None:
return
else:
self.zhongxu(root.left,result)
result.append(root.val)
self.zhongxu(root.right,result)
return result
对称二叉树 12.10
思路:递归
# 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 isSymmetric(self,root):
if root==None:
return True
else:
return self.digui(root.left,root.right)
def digui(self,left,right):
if left==None and right==None:
return True
if left==None or right==None:
return False
if right.val!=left.val:
return False
return self.digui(left.left,right.right) and self.digui(left.right,right.left)
二叉树最大的深度
思路:递归
# 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 maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
num = 1
return self.bianli(root, num)
def bianli(self, root, num):
if root == None:
return 0
else:
num = max(self.bianli(root.left, num),self.bianli(root.right, num))
num = num + 1
return num
二叉树的构建
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def Create_tree(root, llist, i):
if i < len(llist):
if llist[i] == None:
return None
else:
root = TreeNode(llist[i])
root.left = Create_tree(root.left, llist, 2 * i + 1)
root.right = Create_tree(root.right, llist, 2 * i + 2)
return root
return root