当前位置:网站首页>【LeetCode刷题】-数之和专题(待补充更多题目)
【LeetCode刷题】-数之和专题(待补充更多题目)
2022-08-05 02:07:00 【D2O】
LeetCode上关于“x数之和”的题目有如下几道
1 两数之和
1 两数之和
思路:hush map
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hush=[]
for i in range(len(nums)):
temp=target-nums[i]
if temp in hush:
return [hush.index(temp),i]
else:
hush.append(nums[i])
附一个画蛇添足的错误解法:
题目要求返回的是 index ,就不适用这种一上来就 sort 的解法,
由于nums中有重复元素的存在,这种方法不出意外地报错了。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
temp1=nums.copy()
nums.sort()
l,r=0,len(nums)-1
while l<r:
temp=nums[l]+nums[r]
if temp==target:
return [temp1.index(nums[l]),temp1.index(nums[r])]
elif temp<target:
l+=1
else:
r-=1
15 三数之和
15 三数之和
思路:sort 之后用双指针
三数之和题解(其中一种超时了)
18 四数之和
[18 四数之和](https://leetcode.cn/problems/4sum/
思路:还是sort 之后双指针
# TODO:加上代码
633 平方数之和
633 平方数之和
这个题挺简单的,确定检索范围是 range(1, int(math.sqrt(c) + 1))
,
在这个范围内找两个数,使得它们的平方和是目标值,
接下来就是经典的两数和问题了。
Python 开方:math.sqrt(num)
解法1:双指针法
class Solution(object):
def judgeSquareSum(self, c):
if c == 0: return True
n=int(math.sqrt(c))
a,b=0,n
while a<=b:
temp=c-a**2-b**2
if temp ==0:
return True
elif temp>0:
a+=1
else:
b-=1
return False
解法2:暴力计算
注:因为只要b是自然数就符合题目要求,所以就不用辛辛苦苦地遍历list了,直接判断b是否是整数。
判断某数是否为整数:int(num)==num
class Solution(object):
def judgeSquareSum(self, c):
if c == 0: return True
for a in range(1, int(math.sqrt(c) + 1)):
b = c - a * a
if int(math.sqrt(b)) ** 2 == b:
return True
return False
关于双指针的一点思考
双指针的本质是什么?
移动的时候会不会剪掉正确答案?
边栏推荐
猜你喜欢
(17) 51 MCU - AD/DA conversion
IJCAI2022 | DictBert:采用对比学习的字典描述知识增强的预训练语言模型
Transfer Learning - Distant Domain Transfer Learning
J9数字货币论:web3的创作者经济是什么?
Hypervisor related knowledge points
iNFTnews | What can NFTs bring to the sports industry and fans?
在这个超连接的世界里,你的数据安全吗
特殊矩阵的压缩存储
How to simply implement the quantization and compression of the model based on the OpenVINO POT tool
".NET IoT from scratch" series
随机推荐
亚马逊云科技携手中科创达为行业客户构建AIoT平台
dotnet 6 为什么网络请求不跟随系统网络代理变化而动态切换代理
转:查尔斯·汉迪:你是谁,比你做什么更重要
Transfer Learning - Joint Geometrical and Statistical Alignment for Visual Domain Adaptation
std::string::find 返回值的坑
SAP ERP和ORACLE ERP的区别是哪些?
第09章 性能分析工具的使用【2.索引及调优篇】【MySQL高级】
Methods commonly used interface automation test framework postman tests
Leetcode brushing questions - 22. Bracket generation
【日常训练】1403. 非递增顺序的最小子序列
CMS website construction process
leetcode-对称二叉树
C language basics -- pointers
[Machine Learning] 21-day Challenge Study Notes (2)
AI+PROTAC|dx/tx完成500万美元种子轮融资
Dotnet 6 Why does the network request not follow the change of the system network proxy and dynamically switch the proxy?
How to create an rpm package
Residential water problems
[Unity Entry Plan] Handling of Occlusion Problems in 2D Games & Pseudo Perspective
优化Feed流遭遇拦路虎,是谁帮百度打破了“内存墙”?