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

SOM网络2: 代码的实现

教你VSCode如何快速对齐代码、格式化代码

User Experience | How to Measure User Experience?

Advanced Algebra_Proof_The algebraic multiplicity of any eigenvalue of a matrix is greater than or equal to its geometric multiplicity

SOM Network 2: Implementation of the Code

(Translation) How the contrasting color of the button guides the user's actions

xctf攻防世界 Web高手进阶区 webshell

19 Lectures on Disassembly of Multi-merchant Mall System Functions - Invoice Management on the Platform

求解多元多次方程解的个数

Postman 批量测试接口详细教程
随机推荐
Implementation principle of VGUgarbage collector (garbage collector)
Shell programming conditional statement
LeetCode952三部曲之二:小幅度优化(137ms -> 122ms,超39% -> 超51%)
小程序容器+自定义插件,可实现混合App快速开发
xctf attack and defense world web master advanced area webshell
2022 版 MySQL 巅峰教程,收藏好,慢慢看
Delicious this year
number of solutions to solve a multivariate multi-degree equation
小程序毕设作品之微信体育馆预约小程序毕业设计成品(1)开发概要
ImportError: `save_weights` requires h5py. Problem solved
Dichotomy Medium LeetCode6133. Maximum Number of Groups
线上故障排查方案
用户体验 | 如何度量用户体验?
第一讲 测试知多少
线程池分析
【移动Web】移动端适配
long investment career
Today's sleep quality record 74 points
【开源】Sentinel高性能高可用集群限流解决方案
迁移学习——Discriminative Transfer Subspace Learning via Low-Rank and Sparse Representation