contents
- 1. 两数之和
- 7. 整数反转
- 9. 回文数
- 13. 罗马数字转整数
- 14. 最长公共前缀
- 20. 有效的括号
- 21. 合并两个有序链表
- 26. 删除排序数组中的重复项
- 27. 移除元素
- 28. 实现 strStr()
- 35. 搜索插入位置
- 69. x 的平方根
- 38. 外观数列
- 53. 最大子序和
- 300. 最长递增子序列
- 58. 最后一个单词的长度
- 66. 加一
- 67. 二进制求和
- 70. 爬楼梯
- 83. 删除排序链表中的重复元素
- 88. 合并两个有序数组
- 100. 相同的树
- 101. 对称二叉树
- 104. 二叉树的最大深度
- 107. 二叉树的层序遍历 II
- 108. 将有序数组转换为二叉搜索树
- 110. 平衡二叉树
- 111. 二叉树的最小深度
- 112. 路径总和
- 118. 杨辉三角
- 119. 杨辉三角 II
- 121. 买卖股票的最佳时机
- 122. 买卖股票的最佳时机 II
- 125. 验证回文串
- 136. 只出现一次的数字
- 141. 环形链表
- 155. 最小栈
- 1921 消灭怪物的最大数量
- 144. 二叉树的前序遍历
- 145. 二叉树的后序遍历
- 146. 二叉树的中序遍历
- 160 相交链表
1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
- yueyue’s solution
class Solution:
def twoSum(self, nums, target):
n=len(nums)
for i in range(n):
for j in range(i+1,n):
if nums[i]+nums[j]==target:
return i,j
- Dalao’s solution
def twoSum(nums, target):
hashmap={
}
for i,num in enumerate(nums):
if hashmap.get(target - num) is not None:
return [i,hashmap.get(target - num)]
hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况
thinking:该学一学哈希表,《算法图解》第五章待看(后续补充)
7. 整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [ − 2 31 , 2 31 − 1 ] [−2^{31}, 2^{31} − 1] [−231,231−1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
- yueyue’s solution
class Solution:
def reverse(self,x):
sign=1
if x<0:
sign=-1
x=abs(x)
num=int(''.join(list(str(x))[::-1]))
if num<=2**31:
return num*sign
else:
return 0
- Dalao’s solution
class Solution:
def reverse(self,x):
y, res = abs(x), 0
# 则其数值范围为 [−2^31, 2^31 − 1]
boundry = ((1<<31) -1)//10
print(boundry)
ones= ((1<<31) -1)%10 if x>0 else (1<<31)%10
while y != 0:
if (res > boundry) or ((y>ones)and(res == boundry)):
return 0
res = res*10 +y%10
y //=10
return res if x >0 else -res
thinking:要先判断储不储存得下啊 !!切片可能不符合题意啊……
9. 回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
- yueyue’s solution
class Solution:
def isPalindrome(self, x) :
x=str(x)
y=x[::-1]
return x==y
- Dalao’s solution
class Solution:
def isPalindrome(self, x) :
if x<0:
return False
else:
res,y=0,x
while y!=0:
res=res*10+y%10
y//=10
return res==x
thinking:特殊情况,如是负数则一定不是回文数,直接返回 false
13. 罗马数字转整数
- yueyue’s solution=Dalao’s
class Solution:
def romanToInt(self, s) :
n=0
R_dict = {
'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
for i in range(len(s)):
if i!=len(s)-1 and R_dict[s[i]] <R_dict[s[i+1]]:
n-=R_dict[s[i]]
else:
n+=R_dict[s[i]]
return n
14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
- yueyue’s solution
class Solution:
def longestCommonPrefix(self,strs):
same_pre=""
index=0
if ""in strs or strs==[]:
return same_pre
elif len(strs)==1:
return strs[0]
else:
while index<len(strs[0]):
same_pre+=strs[0][index]
for s in strs[1:]:
if index<len(s) and s[index]!=same_pre[index]:
return same_pre[:-1]
elif index==len(s):
return same_pre[:-1]
index+=1
return same_pre
2.yueyue’s improvement
class Solution:
def longestCommonPrefix(self,strs):
if strs==[]:
return ""
for i in range(len(strs[0]),0,-1):
tem=strs[0][:i]
for s in strs[1:]:
if s[:i]!=tem:
break
else:
return tem
return ""
20. 有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
yueyue’s solution
class Solution:
def isValid(self, s: str) -> bool:
pare_dict={
'(':')','{':'}','[':']'}
right=[]
for i in s:
if i in pare_dict:
right.append(pare_dict.get(i))
elif right:
if i==right.pop():
continue
else:
return False
else:
return False
if right==[]:
return True
else:
return False
- Dalao’s solution
class Solution:
def isValid(self, s: str) -> bool:
pare_dict={
'(':')','{':'}','[':']'}
right=[]
for i in s:
if i in pare_dict:
right.append(pare_dict.get(i))
elif right:
if i==right.pop():
continue
else:
return False
else:
return False
return not right
21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
- yueyue’s solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur1=l1
cur2=l2
new=ListNode()
cur3=new
while cur1!=None and cur2!=None:
if cur1.val<=cur2.val:
cur3.next=ListNode(cur1.val)
cur1=cur1.next
elif cur1.val>cur2.val:
cur3.next=ListNode(cur2.val)
cur2=cur2.next
cur3=cur3.next
if cur1!=None: cur3.next=cur1
if cur2!=None: cur3.next=cur2
return new.next
- Dalao’s solution
递归用的太妙了
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1==None:
return l2
if l2==None:
return l1
if l1.val<=l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2
26. 删除排序数组中的重复项
给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
- yueyue’s solution
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
for i in nums:
n_count=nums.count(i)
if n_count>1:
for j in range(n_count-1):
nums.remove(i)
return len(nums)
- yueyue’s impovement
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
y=1
for i in range(1,len(nums)):
if nums[i-1]<nums[i]:
nums[y]=nums[i]
y+=1
return y
- Dalao’s solution
双指针
def removeDuplicates(nums):
i=0
j=1
while j<len(nums):
if nums[j]>nums[i]:
i+=1
nums[i]=nums[j]
j+=1
return i+1
27. 移除元素
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
- yueyue’s solution
class Solution:
def removeElement(self, nums, val):
i=0
for j in range(len(nums)<