1.两数之和
#缩进可能有点问题,不知道如何简便的调整。-。-
##最基本的,两个for循环
##提交时间超出限制
class Solution:
def twoSum(self,nums,target):
n = len(nums)
for x in range(n):
for y in range(n):
if (nums[x]+nums[y]==target)&(x<y):
return x,y
#两层for循环
#第二层循环遍历x之后的数据
class Solution:
def twoSum(self,nums,target):
n = len(nums)
for x in range(n):
for y in range(x+1,n):
if nums[x] + nums[y] == target:
return x,y
break
else:
continue
#一层for循环,判断target-num[x]是否在nums中,且索引不为x
class Solution:
def twoSum(self,nums,target):
n = len(nums)
for x in range(n):
a=target-nums[x]
if a in nums:
y=nums.index(a)
if x !=y:
return x,y
break
else:
continue
else:
continue
#改进上个方法
#一层for循环,判断target-num[x]是否在nums的x索引之前的位置,可以节省一半时间
class Solution:
def twoSum(self,nums,target):
n = len(nums)
for x in range(n):
a=target-nums[x]
b=nums[:x]
if a in b:
y=nums.index(a)
return x,y
break
else:
continue
2.整数反转
#代码1
#最基本的str赋值吧,也可以直接用reverse函数或者[::-1]来做。会简单很多
#首先判断x取值,直接溢出或为0时return 0
#判断x正负,根据正负赋予空str,
#再由for循环判断末位是否为0,是的话继续判断倒数第二位,并计数,直到不为0的一位停止。否的话直接赋值......
#上一步可以直接省去,因为int转换可以直接略去字符串首位的0,见代码2
class Solution:
def reverse(self, x):
if (-2**31 <= x <= 2**31 - 1) & (x!=0) :
strx=str(x)
a=len(strx)
n=0
z=''
if x<0:
z='-'
if strx[a-1]!='0':
for i in range(1,a):
z=z+strx[a-i]
else:
for j in range(-a+1,0):
if strx[-j]=='0':
n=n+1
else:
break
for p in range(-a+1+n,0):
z=z+strx[-p]
else:
if strx[a-1]!='0':
for i in range(0,a):
z=z+strx[a-i-1]
else:
for j in range(-a+1,1):
if strx[-j]=='0':
n=n+1
else:
break
for p in range(-a+1+n,1):
z=z+strx[-p]
z1=int(z)
return z1 if -2**31 <= z1 <= 2**31 - 1 else 0
else:
return 0
#代码2
#将末尾判断是否0省去,因为int转换能够直接将字符串首位的0略去
#int('-001230')=-1230
class Solution:
def reverse(self, x):
if (-2**31 <= x <= 2**31 - 1) & (x!=0) :
strx=str(x)
a=len(strx)
n=0
z=''
if x<0:
z='-'
for i in range(1,a):
z=z+strx[a-i]
else:
for i in range(0,a):
z=z+strx[a-i-1]
z1=int(z)
return z1 if -2**31 <= z1 <= 2**31 - 1 else 0
else:
return 0
#代码3
#使用[::-1]进行反转
class Solution:
def reverse(self, x):
if (-2**31 <= x <= 2**31 - 1) & (x!=0) :
strx=str(x)
a=len(strx)
z=''
if x<0:
z='-'+strx[-1:-a:-1]
else:
z=strx[::-1]
z1=int(z)
return z1 if -2**31 <= z1 <= 2**31 - 1 else 0
else:
return 0
3.回文数判断
#直接反转,判断是否相等。
#运行时间短,但内存占用大
#可考虑仅反转后半部分。
class Solution:
def isPalindrome(self, x):
strx=str(x)
b=len(strx)
z=strx[::-1]
if z==strx:
return True
else:
return False
13.罗马数字转整数
#判断罗马数->字符串中 ,第i个代表值与第i+1个值大小,若第i个小,则减去该值,否则加上
#LDVI-> -50+500+5+1=456
class Solution:
def romanToInt(self, s: str) -> int:
Roman2Int ={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
Int = 0
n = len(s)
for index in range(n - 1):
if Roman2Int[s[index]] < Roman2Int[s[index + 1]]:
Int -= Roman2Int[s[index]]
else:
Int += Roman2Int[s[index]]
return Int + Roman2Int[s[-1]]
14.最长公共前缀
##字符串大小比较规则
#当两个字符串比较时,先比较第一位的ASCII编码大小,谁第一位大则谁大,若相同,在比较第二位。。。。。。
#
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return "" #判断是否是空字符串列表
str0 = min(strs)
str1 = max(strs)
for i in range(len(str0)):
if str0[i] != str1[i]:
return str0[:i]
return str0
20.有效的括号
#栈
#https://blog.csdn.net/qq_37941538/article/details/90138129
#入栈:stack.push,stack.append
#出栈:stack.pop
#栈顶元素:stack.peek
#判断栈是否为空:stack.is_Empty()
#stack为空时stack.pop报错
#定义字典,栈为空时pop报错。
#循环s,如果遇到左括号,入栈;遇到右括号,判断此时右括号与栈的出栈元素是否相同,不相同则返回False
#若最后全部循环完毕,返回包含?的栈的长度是否为1,为1则说明所有元素均匹配。不为1说明存在左括号不匹配
class Solution:
def isValid(self, s: str) -> bool:
dic = {'{': '}', '[': ']', '(': ')', '?': '?'}
stack = ['?']
for c in s:
if c in dic: stack.append(c)
elif dic[stack.pop()] != c: return False
return len(stack) == 1
###栈的应用2--十进制转化为2进制,
##除2取余法。将余数送上往下push进栈,全部push完成后,再pop出,实现翻转,即为2进制数
def decimal_to_bin(dec):
stack = Stack()
bin_str = ''
if dec == 0:
stack.push(0)
while dec > 0:
a = dec % 2
stack.push(a)
dec = int(dec / 2)
while not stack.is_Empty():
bin_str += str(stack.pop())
return bin_str
21.合并两个有序链表
#定义链表
class Node:
def __init__(self,val = None, next = None):
self.val = val
self.next = next
#创建链表
在这里插入代码片
L1 = Node(1)
node2 = Node(2)
node3 = Node(4)
L1.next = node2
node2.next = node3
#链表打印
def printList(node):
while node != None:
print (node.val)
node = node.next
printList(L2)
#递归
#-https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/yi-kan-jiu-hui-yi-xie-jiu-fei-xiang-jie-di-gui-by-/
def mergeTwoLists(l1,l2):
if not l1: return l2 # 终止条件,直到两个链表都空
if not l2: return l1
if l1.val <= l2.val: # 递归调用
l1.next = mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = mergeTwoLists(l1,l2.next)
return l2
26.删除排序数组中的重复项
#pop(i)时间复杂度为n,慢
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
a = 0
b = 1
while b < len(nums):
if nums[a] == nums[b]:
nums.pop(a)
else:
a += 1
b += 1
return len(nums)
#直接修改前k个数,因此无需删除操作
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
a = 0
b = 1
while b < len(nums):
if nums[b] == nums[a]:
b += 1
else:
a += 1
nums[a] = nums[b]
return a+1
27.删除排序数组中的重复项
#还是pop ,复杂度还有点高,可以修改
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
a=0
while a < len(nums):
if nums[a] == val:
nums.pop(a)
else:
a+=1
28.实现 strStr()
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
else:
i=len(needle)
j=0
while j <= len(haystack)-i:
a=haystack[j:j+i]
if a == needle:
return j
j+=1
return -1
35.搜索插入位置
#二分法
#无论target在不在nums内,最终都返回left=right
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
right,left = 0,len(nums)
while right < left:
mid=(right+left)//2
if nums[mid] < target:
right = mid+1
else:
left = mid
return right
38.外观数列
#递归
1
11
21
1211
111221
class Solution:
def countAndSay(self, n: int) -> str:
num=1
res=''
if n == 1:
return '1'
else:
next_str=self.countAndSay(n-1)
for i in range (len(next_str)):
if i+1<len(next_str) and next_str[i]==next_str[i+1]:
num=num+1
else:
res=res+str(num)+next_str[i]
num=1
return res
53. 最大子序和
'''
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
'''
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
temp=nums[0] ##保存当前值
max_ = temp ##保存最大值
for i in range (1,len(nums)):
if temp > 0:
temp = temp +nums[i]
max_=max(max_,temp)
else:
temp = nums[i]
max_ =max(max_,temp)
return max_
58. 最后一个单词的长度
'''
输入: "Hello World"
输出: 5
'''
class Solution:
def lengthOfLastWord(self, s: str) -> int:
str_list = s.split()
if len(str_list) > 0:
a=str_list[-1]
b=len(a)
return b
else:
return 0
66. 加一
'''
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
注意199,999等。。。
'''
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
if digits[-1] != 9: ##判断末尾是否为9
digits[-1]=digits[-1]+1
return digits
else:
i=-1
while digits[i] == 9 and -i < len(digits): ##从后往前判断中间位是否连续为9 ,为9则变为0
digits[i] = 0
i=i-1
if -i >= len(digits) and digits[i] == 9: ###判断i是否为首位,且首位是否为9 ,为9则变为0并在首位插入1
digits[i] = 0
digits.insert(0,1)
else: #否则第i位+1()
digits[i] += 1
return digits
67. 二进制求和
class Solution:
def addBinary(self, a: str, b: str) -> str:
inta=0
intb=0
for i in range (len(a)): #二进制转十进制
inta=inta+int(a[i])*2**(len(a)-1-i)
for j in range (len(b)):
intb=intb+int(b[j])*2**(len(b)-1-j)
c=inta+intb
if c == 0:
return '0'
def Dec2Bin(dec): #十进制转二进制-递归
result = ''
if dec:
result = Dec2Bin(dec // 2)
return result + str(dec % 2)
else:
return result
return Dec2Bin(c)
69. x 的平方根
#二分法
'''
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
'''
class Solution:
def mySqrt(self, x: int) -> int:
left=0
right=x
mid=0
while int(left) != int(right) :
mid=(left+right)/2
if mid**2 > x:
right = mid
else:
left = mid
return int(left)
70.爬楼梯
'''
动态规划###
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
'''
class Solution:
def climbStairs(self, n: int) -> int:
d=[0]*(n+2)
d[1]=1
d[2]=2
for i in range (3,n+1):
d[i]=d[i-1]+d[i-2]
return d[n]
#节省内存
class Solution:
def climbStairs(self, n: int) -> int:
if n<2:
return n
a=1
b=2
for i in range (3,n+1):
a,b=b,a+b
return b
83. 删除排序链表中的重复元素
'''
输入: 1->1->2->3->3
输出: 1->2->3
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
ret=head
while head != None and head.next != None:
if head.val == head.next.val:
head.next = head.next.next
else:
head=head.next
return ret
88. 合并两个有序数组
'''
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
'''
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
i = m + n - 1
while n > 0:
if m > 0 and nums1[m-1] > nums2[n-1]:
nums1[i] = nums1[m-1]
m -= 1
else:
nums1[i] = nums2[n-1]
n -= 1
i -= 1
118. 杨辉三角
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
a = []
if numRows == 0:
return a
a = [[1]]
for i in range (1,numRows):
b=[1]*(i+1)
for j in range (1,i):
b[j]=a[i-1][j-1]+a[i-1][j]
a.append(b)
return a
119. 杨辉三角 II
输入: 3
输出: [1,3,3,1]
错位相加法
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
res=[1]
while len(res) <= rowIndex:
res=[i+j for i,j in zip(res+[0],[0]+res)]
return res
动态规划
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
d=[0]*(rowIndex+2)
d[1]=[1]
if rowIndex == 0:
return d[1]
d[2]=[1,1]
for i in range (3,rowIndex+2):
d[i]=[i+j for i,j in zip(d[i-1]+[0],[0]+d[i-1])]
return d[rowIndex+1]
动态规划改版-节省内存
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
a=[1]
if rowIndex == 0:
return a
for i in range (2,rowIndex+2):
a=[i+j for i,j in zip(a+[0],[0]+a)]
return a
121. 买卖股票的最佳时机
动态规划 前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
else:
dp =0
temp=prices[0]
for i in range(1,len(prices)):
temp = min(temp,prices[i])
dp=(max(dp,prices[i]-temp))
return dp
122. 买卖股票的最佳时机 II
只要昨天比今天价格低,则昨天买入今天卖出。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range (1,len(prices)):
if prices[i-1] <= prices[i]:
profit=profit+(prices[i]-prices[i-1])
return profit
125. 验证回文串
b.isalnum():判断b是否为字母或数字
b.lower() :将b转为小写
class Solution:
def isPalindrome(self, s: str) -> bool:
gzw = ''.join(b.lower() for b in s if b.isalnum())
return gzw[::-1] == gzw
双指针
class Solution:
def isPalindrome(self, s: str) -> bool:
gzw = ''.join(b.lower() for b in s if b.isalnum())
left,right = 0,len(gzw)-1
while left < right:
if gzw[left] != gzw[right]:
return False
left,right=left+1,right-1
return True
136. 只出现一次的数字
输入: [4,1,2,1,2]
输出: 4
异或运算:两个数字异或的结果a^b是将 a 和 b 的二进制每一位进行运算,
得出的数字。 运算的逻辑是如果同一位的数字相同则为0,不同则为1。
a^a=0
a^0=a
a^b^a=b^a^a=b^(a^a)=b^0=b
class Solution:
def singleNumber(self, nums: List[int]) -> int:
r=0
for i in nums:
r=r^i
return r
141. 环形链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow,fast = head,head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
if fast == slow:
return True
return False