7-整数反转(python)
class Solution(object):
def reverse(self, x):
y, res = abs(x), 0
# 则其数值范围为 [−2^31, 2^31 − 1]
boundry = (1<<31) -1 if x>0 else 1<<31
while y != 0:
res = res*10 +y%10
if res > boundry :
return 0
y //=10
return res if x >0 else -res
8-字符串转整数(python)
#正则
class Solution(object):
def myAtoi(self, str):
INT_MAX = 2147483647
INT_MIN = -2147483648
str = str.lstrip() #清除左边多余的空格
num_re = re.compile(r'^[\+\-]?\d+') #设置正则规则
num = num_re.findall(str) #查找匹配的内容
num = int(*num) #由于返回的是个列表,解包并且转换成整数
return max(min(num,INT_MAX),INT_MIN) #返回值
9-是否为回文数(python)
#双指针
class Solution:
def isPalindrome(self, x: int) -> bool:
lst=list(str(x))
l,r=0,len(lst)-1
while l<r:
if lst[l]!=lst[r]:
return False
l+=1
r-=1
return True
14-最长公共前缀(python)
#水平扫描
class Solution:
def longestCommonPrefix(self,strs):
if not strs:return ''
if len(strs)<2:
return strs[0]
res=strs[0]
for i in range(1,len(strs):
if not strs[i]:return ''
min_len=min(len(res),len(strs[i])
tmp=''
for j in range(min_len):
if res[j]==strs[i][j]:
tmp+=res[j]
else:
break
res=tmp
return res
16-最接近的三数之和(python)
class Solution(object):
def threeSumClosest(self, nums, target):
n=len(nums)
if(not nums or n<3):
return None
nums.sort()
res=float("inf")
for i in range(n):
if(i>0 and nums[i]==nums[i-1]):
continue
L=i+1
R=n-1
while(L<R):
cur_sum=nums[i]+nums[L]+nums[R]
if(cur_sum==target):
return target
if(abs(cur_sum-target)<abs(res-target)):
res=cur_sum
if(cur_sum-target<0):
L+=1
else:
R-=1
return res
26-删除重复项(python)
class Solution(object):
def removeDuplicates(self, nums):
flag=0
if len(nums)==0:
return 0
for i in range(len(nums)):
if nums[i]!=nums[flag]:
flag+=1
nums[flag]=nums[i]
return flag+1
43-字符串相乘(python)
#乘+进位
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == "0" or num2 == "0": #处理特殊情况
return "0"
l1, l2 = len(num1), len(num2)
if l1 < l2:
num1, num2 = num2, num1 #保障num1始终比num2大
l1, l2 = l2, l1
num2 = num2[::-1]
res = "0"
for i, digit in enumerate(num2):
tmp = self.StringMultiplyDigit(num1, int(digit)) + "0" * i #计算num1和num2的当前位的乘积
res = self.StringPlusString(res, tmp) #计算res和tmp的和
return res
def StringMultiplyDigit(self,string, n):
#这个函数的功能是:计算一个字符串和一个整数的乘积,返回字符串
#举例:输入为 "123", 3, 返回"369"
s = string[::-1]
res = []
for i, char in enumerate(s):
num = int(char)
res.append(num * n)
res = self.CarrySolver(res)
res = res[::-1]
return "".join(str(x) for x in res)
def CarrySolver(self, nums):
#这个函数的功能是:将输入的数组中的每一位处理好进位
#举例:输入[15, 27, 12], 返回[5, 8, 4, 1]
i = 0
while i < len(nums):
if nums[i] >= 10:
carrier = nums[i] // 10
if i == len(nums) - 1:
nums.append(carrier)
else:
nums[i + 1] += carrier
nums[i] %= 10
i += 1
return nums
def StringPlusString(self, s1, s2):
#这个函数的功能是:计算两个字符串的和。
#举例:输入为“123”, “456”, 返回为"579"
#PS:LeetCode415题就是要写这个函数
l1, l2 = len(s1), len(s2)
if l1 < l2:
s1, s2 = s2, s1
l1, l2 = l2, l1
s1 = [int(x) for x in s1]
s2 = [int(x) for x in s2]
s1, s2 = s1[::-1], s2[::-1]
for i, digit in enumerate(s2):
s1[i] += s2[i]
s1 = self.CarrySolver(s1)
s1 = s1[::-1]
return "".join(str(x) for x in s1)
53-最大自序和(python)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
sum=nums[0]
max_=nums[0]
for i in range(1,len(nums)):
if sum>0:
sum+=nums[i]
max_=max(max_,sum)
else:
sum=nums[i]
max_=max(max_,sum)
return max_
54-螺旋矩阵(python)
class Solution(object):
def spiralOrder(self, matrix):
res=[]
m=len(matrix)
if m==0:
return res
else:
n=len(matrix[0])
if n==0:
return res
count=(m+1)//2
k=0
su=m*n
cc=0
while k<count and cc<su:
for i in range(k,n-k):
res.append(matrix[k][i])
cc+=1
for i in range(k+1,m-1-k):
res.append(matrix[i][n-1-k])
cc+=1
if k!=m-1-k:
for i in range(k,n-k):
res.append(matrix[m-1-k][n-1-i])
cc+=1
if k!=n-1-k:
for i in range(k+1,m-1-k):
res.append(matrix[m-1-i][k])
cc+=1
k+=1
return res
59-螺旋矩阵2(python)
class Solution(object):
def generateMatrix(self, n):
l, r, t, b = 0, n - 1, 0, n - 1#左右上下
mat = [[0 for _ in range(n)] for _ in range(n)]
num, tar = 1, n * n
while num <= tar:
for i in range(l, r + 1): # left to right
mat[t][i] = num
num += 1
t += 1
for i in range(t, b + 1): # top to bottom
mat[i][r] = num
num += 1
r -= 1
for i in range(r, l - 1, -1): # right to left
mat[b][i] = num
num += 1
b -= 1
for i in range(b, t - 1, -1): # bottom to top
mat[i][l] = num
num += 1
l += 1
return mat
61-旋转链表(python)
#连成环,找到节点断开
class Solution:
def rotateRight(self,head,k):
if not head:return head
ptr=head
num=1
while ptr.next:
ptr=ptr.next
num+=1
ptr.next=head#环一起
count=num-k%num
while count:
ptr=head
head=head.next
count-=1
pte
88-合并两个有序数组,将num2合并到num1(python)
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
while n:
if m == 0:
nums1[n-1] = nums2[n-1]
n -= 1
continue
if nums1[m-1] < nums2[n-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else:
nums1[m+n-1]= nums1[m-1]
m -= 1
return nums1
89-格雷码(python)
class Solution(object):
def grayCode(self, n):
res, head = [0], 1
for i in range(n):
for j in range(len(res) - 1, -1, -1):
res.append(head + res[j])
head <<= 1
return res
122-买卖股票的最佳时机2(python)
#看成每天都买卖
class Solution:
def maxprofit(self,prices):
profit=0
for i in range(1,len(prices)):
tmp=prices[i]-prices[i-1]
if tmp>0:
profit+=tmp
return profit
230-二叉搜索树第k小的元素(python)
#二叉搜索树的中序 有序
class Solution:
def kthSmallest(self,root,k):
res=[]
def helper(self,node):
if not node:return res
helper(node.left)
res.append(node.val)
helper(node.right)
helper(root)
return res[k-1]
235-二叉搜索树的最近公共祖先(python)
#分为在左子树 右子树以及两边
class Solution:
def lowestCommonAncestor(self,root,p,q):
if p.val<root.val and q.val<root.val:
return self.lowestCommonAncestor(root.left,p.q)
elif p.val>root.val and q.val>root.val:
return self.lowestCommonAncestor(root.right,p,q)
else:
return root
231-判断是否为2的幂(python)
class Solution(object):
def isPowerOfTwo(self, n):
return n>0 and n&(n-1)==0
237-删除链表中的节点(python)
class Solution:
def deletenode(self,node):
node.val=node.next.val
node.next=node.next.next
292-Nim游戏(python)
class Solution:
def canwinNim(self,n):
return (n%4)!=0
344-反转字符串(python)
class Solution:
def reverseString(self,s):
i,j=0,len(s)-1
while i<j:
s[i],s[j]=s[j],s[i]
i+=1
j-=1
557-反转字符串中的单次2(python)
class Solution:
def reverseWords(self,s):
s=s+" "
stack,res=[],""
for i in s:
stack.append(i)
if i==" ":
while(stack):
res=res+stack.pop()
return res[1:]