0
点赞
收藏
分享

微信扫一扫

LeetCode刷题(9、11、12、14、15)


目录

​​一、回文数​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

​​ 二、盛最多水的容器​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

​​三、整数转罗马数字​​

​​1、题目描述​​

​​2、题解​​

​​3、源码 ​​

​​四、三数之和​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

​​五、最长公共前缀​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

一、回文数

1、题目描述

LeetCode刷题(9、11、12、14、15)_罗马数字

2、题解

LeetCode刷题(9、11、12、14、15)_罗马数字_02

3、源码

class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
if (s[::] == s[::-1]):
return True
else:
return False

 二、盛最多水的容器

1、题目描述

LeetCode刷题(9、11、12、14、15)_最长公共前缀_03

2、题解

LeetCode刷题(9、11、12、14、15)_罗马数字_04

3、源码

# class Solution:
# def maxArea(self, height: List[int]) -> int:
# max = 0
# for i in range(len(height)):
# for j in range(i + 1,len(height)):
# min = height[i]
# if (min > height[j]):
# min = height[j]
# s = min * (j - i)
# if (s > max):
# max = s
# return max

class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
ans = 0
while l < r:
area = min(height[l], height[r]) * (r - l)
ans = max(ans, area)
if height[l] <= height[r]:
l += 1
else:
r -= 1
return ans

三、整数转罗马数字

1、题目描述

LeetCode刷题(9、11、12、14、15)_罗马数字_05

LeetCode刷题(9、11、12、14、15)_最长公共前缀_06

2、题解

LeetCode刷题(9、11、12、14、15)_罗马数字_07

3、源码 

class Solution:
def intToRoman(self, num: int) -> str:
Roman = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),]
ans = ''
for n,roman_num in Roman:
while num >= n:
num -= n
ans += roman_num
if num == 0:
break
return ans

四、三数之和

1、题目描述

LeetCode刷题(9、11、12、14、15)_罗马数字_08

2、题解

LeetCode刷题(9、11、12、14、15)_罗马数字_09

3、源码

class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if len(nums) <= 2:
return []
nums.sort()#排序,双指针
ans = []
for i in range(len(nums)):
if(nums[i] > 0):
return ans
if (i > 0 and nums[i] == nums[i - 1]):
continue
L = i + 1
R = n - 1
while (L < R):
if (nums[i] + nums[L] + nums[R] == 0):
ans.append([nums[i],nums[L],nums[R]])
while(L < R and nums[L] == nums[L+1]):
L += 1
while(L < R and nums[R] == nums[R-1]):
R -=1
L +=1
R -=1
elif (nums[i] + nums[L] +nums[R] > 0):
R -=1
else:
L +=1

return ans


五、最长公共前缀

1、题目描述

LeetCode刷题(9、11、12、14、15)_python_10

2、题解

LeetCode刷题(9、11、12、14、15)_最长公共前缀_11

3、源码

class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ''
for i in zip(*strs):
if len(set(i)) == 1:
ans += i[0]
else:
break
return ans

举报

相关推荐

0 条评论