当前位置:网站首页>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));
?>
边栏推荐
猜你喜欢

Deep Learning Course2 Week 2 Optimization Algorithms Exercises
![[深入研究4G/5G/6G专题-48]: 5G Link Adaption链路自适应-4-下行链路自适应DLLA-PDCCH信道](/img/6b/d4ff120493e878fcf5c9aa728eced7.png)
[深入研究4G/5G/6G专题-48]: 5G Link Adaption链路自适应-4-下行链路自适应DLLA-PDCCH信道

一种灵活的智能合约协作方式

Flutter基础学习(一)Dart语言入门

威纶通触摸屏如何打开并升级EB8000旧版本项目并更换触摸屏型号?

feel so stupid

Centos7--MySQL的安装

找工作必备!如何让面试官对你刮目相看,建议收藏尝试!!

Shell programming conditional statement

shell specification and variables
随机推荐
scikit-learn no moudule named six
[Niu Ke brush questions-SQL big factory interview questions] NO4. Travel scene (a taxi)
APP special test: traffic test
还在纠结报表工具的选型么?来看看这个
Dichotomy Medium LeetCode6133. Maximum Number of Groups
编曲软件FL studio20.8中文版功能和作用
SAP Spartacus Accessibility E2E 端到端测试
kubernetes CoreDNS全解析
xctf攻防世界 Web高手进阶区 web2
自建 Prometheus 采集腾讯云容器服务监控数据最佳实践
第3讲:MySQL数据库中常见的几种表字段数据类型
xctf attack and defense world web master advanced area webshell
SOM网络2: 代码的实现
入门数据库Days4
Lecture 3: Several common table field data types in MySQL database
使用Jenkins做持续集成,这个知识点必须要掌握
[机缘参悟-58]:《素书》-5-奉行仁义[遵义章第五]
小程序毕设作品之微信美食菜谱小程序毕业设计成品(5)任务书
Homework 8.1 Orphans and Zombies
高等代数_证明_矩阵的任意特征值的代数重数大于等于其几何重数