当前位置:网站首页>PHP算法之最接近的三数之和
PHP算法之最接近的三数之和
2022-08-01 22:08:00 【phpstory】
<?php
function threeSumClosest($nums, $target) {
sort($nums);
$count = count($nums);
$ans = $nums[0] + $nums[1] + $nums[2];
for( $i=0;$i<$count;$i++) {
$start = $i+1; $end = $count - 1;
while($start < $end) {
$sum = $nums[$start] + $nums[$end] + $nums[$i];
if(abs($target - $sum) < abs($target - $ans)){
$ans = $sum;
}
if($sum > $target){
$end--;
}
else if($sum < $target){
$start++;
}
else{
return $ans;
}
}
}
return $ans;
}
var_dump(threeSumClosest(array(-1,2,1,-4,0),1));
?>
边栏推荐
- The thing about npm
- Prufer sequence
- VGUgarbage collector(垃圾回收器)的实现原理
- Still struggling with reporting tool selection?To take a look at this
- MySQL related knowledge
- 用户体验 | 如何度量用户体验?
- 熟悉的朋友
- 小程序毕设作品之微信体育馆预约小程序毕业设计成品(2)小程序功能
- 三、mysql 存储引擎-建库建表操作
- 论文解读(GSAT)《Interpretable and Generalizable Graph Learning via Stochastic Attention Mechanism》
猜你喜欢
随机推荐
小程序毕设作品之微信体育馆预约小程序毕业设计成品(2)小程序功能
xctf attack and defense world web master advanced area web2
还在纠结报表工具的选型么?来看看这个
The must-have "fishing artifact" for programmers is here!
(*゚ヮ゚)*【精品C语言整理】*(゚ヮ゚*)女盆友缠着你让你教她写代码怎么办?安排,三万字博文带你走遍C语言,从此不再害怕编程
PAM 回文自动机
熟悉的朋友
如何防范 DAO 中的治理攻击?
今年的很美味
【C语言】猜数字小游戏
AIDL communication
feel so stupid
高等代数_证明_矩阵的任意特征值的代数重数大于等于其几何重数
Analysis of the development trend of game metaverse
How to add a game character to a UE4 scene
Advanced Algebra_Proof_The algebraic multiplicity of any eigenvalue of a matrix is greater than or equal to its geometric multiplicity
三、mysql 存储引擎-建库建表操作
MySQL related knowledge
2022 edition of MySQL tutorial, top collection good, take your time
小程序毕设作品之微信美食菜谱小程序毕业设计成品(7)中期检查报告









