回文数
双指针解法
我是先把数字转化成列表,在前后一次匹配,如果匹配不上了就不是。
现在想想好像不必要保存在列表里面,提取的时候直接进行匹配就好了,还省了内存。
class Solution:
def isPalindrome(self, x: int) -> bool:
if(x<0):
return False
else:
r = abs(x)
re = []
while(r>=10):
temp = r%10
re.append(temp)
r = int(r/10)
re.append(r)
low = 0
high = len(re)-1
while(low<high):
if re[low]==re[high]:
low+=1
high -= 1
else:
return False
return True
x = 0
b = Solution().isPalindrome(x)
print(b)
整数转罗马数字
解题思路:每一次提取数字的最后一个数,将之转化成罗马数字,那问题就变成了,在个十百千位时,罗马数字表示不同,所以用不同的列表保存不同的表示就可以了。
class Solution:
def intToRoman(self, num: int) -> str:
remainder = 0
re = num
i=1
str =''
while(re >= 10):
remainder = re % 10
re = int(re/10)
Restr = self.ToRome(remainder,i)
i+=1
str = Restr + str
Restr = self.ToRome(re, i)
str = Restr + str
return str
def ToRome(self,num,i):
if i == 1:
rome = ['I', 'V', 'X']
elif i == 2:
rome = ['X', 'L', 'C']
elif i == 3:
rome = ['C', 'D', 'M']
else:
rome = ['M']
if num<4:
str = rome[0]*num
elif num == 4:
str = rome[0]+rome[1]
elif num == 5:
str = rome[1]
elif num<9:
str = rome[1]+rome[0]*(num-5)
else:
str = rome[0]+rome[2]
return str
x=100
str = Solution().intToRoman(x)
print(str)
盛最多水的容器
解题:
这一题说白了就是一道面积题,用两边挡板的最矮挡板去乘两挡板距离得到面积,本来我是用暴力法去求解这题,但是这样在leetcode上会显示超时。
然后我用了双指针法,
思路:一个指针指向第一个挡板,一个指针指向最后一个挡板,然后高的矮的去向中间移,如果面积变大了,就更新最大面积,当然在移的过程中,如果遇到更矮的可以直接跳过。
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
length = len(height)
if(length<2):
return 0
'''
for i in range(0,length):
for j in range(i+1,length):
A = height[i]*(j-i) if height[i]<height[j] else height[j]*(j-i)
if(A>maxA):
maxA = A
'''
low = 0
high = length-1
maxA = height[low]*(high - low) if height[low]<height[high] else height[high]*(high - low)
while(low<high):
if(height[low]<height[high]):
i = 1
while(height[low+i] <height[low]):
i+=1
low = low+i
if (high <= low):
return maxA
A = height[low]*(high - low) if height[low]<height[high] else height[high]*(high - low)
if(A>maxA):
maxA = A
else:
i = 1
while (height[high - i] < height[high]):
i += 1
high = high - i
if(high<=low):
return maxA
A = height[low] * (high - low) if height[low] < height[high] else height[high] * (high - low)
if (A > maxA):
maxA = A
height =
result = Solution().maxArea(height)
print(result)
letcode 整数反转
class Solution:
def reverse(self, x: int) -> int:
y = x
remainder = []
signal = 0 if x < 0 else 1
y = abs(x)
while(y>=10):
remainder.append(y % 10)
y = int(y / 10)
result = 0
for i in remainder:
result = result*10 + i
if signal == 1:
if result*10+y >= 2**31-1:
return 0
else:
return result*10+y
else:
if signal == 0:
if result*10 + y>=2**31:
return 0
else:
return -(result*10+y)
x = 0
a = Solution().reverse(x)
print(a)