当前位置:网站首页>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));
?>
边栏推荐
- AQS
- Prufer sequence
- 2022 edition of MySQL tutorial, top collection good, take your time
- 网络水军第一课:手写自动弹幕
- ImportError: `save_weights` requires h5py. Problem solved
- leetcode 204. Count Primes 计数质数 (Easy)
- LeetCode952三部曲之一:解题思路和初级解法(137ms,超39%)
- 【建议收藏】ヾ(^▽^*)))全网最全输入输出格式符整理
- Shell programming conditional statement
- 【C语言实现】两种计算平均成绩题型,博主精心整理,值得一读
猜你喜欢
程序员必备的 “ 摸鱼神器 ” 来了 !
(翻译)按钮的对比色引导用户操作的方式
迁移学习——Discriminative Transfer Subspace Learning via Low-Rank and Sparse Representation
移动端人脸风格化技术的应用
How to add a game character to a UE4 scene
KMP 字符串匹配问题
【开源】Sentinel高性能高可用集群限流解决方案
MySQL related knowledge
blender3.2.1 unit setting
(Translation) How the contrasting color of the button guides the user's actions
随机推荐
2022 版 MySQL 巅峰教程,收藏好,慢慢看
[机缘参悟-58]:《素书》-5-奉行仁义[遵义章第五]
[Mobile Web] Mobile terminal adaptation
HCIP---Multiple Spanning Tree Protocol related knowledge points
Graph Theory - Strongly Connected Component Condensation + Topological Sort
NgRx Store createSelector 的单步调试和源代码分析
SAP Spartacus Accessibility E2E 端到端测试
小程序毕设作品之微信体育馆预约小程序毕业设计成品(4)开题报告
0DFS Medium LeetCode6134. Find the closest node to the given two nodes
Postman 批量测试接口详细教程
【牛客刷题-SQL大厂面试真题】NO4.出行场景(某滴打车)
03、GO语言变量定义、函数
9. SAP ABAP OData 服务如何支持删除(Delete)操作
递归(各经典例题分析)
小程序毕设作品之微信美食菜谱小程序毕业设计成品(7)中期检查报告
如何防范 DAO 中的治理攻击?
字符串——Trie
2022-08-01 第八组 曹雨 泛型 枚举
第一讲 测试知多少
Prufer sequence