LeetCode - 最接近的三数之和
2022/7/23 23:26:37
本文主要是介绍LeetCode - 最接近的三数之和,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
最接近的三数之和
你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
示例 2:
输入:nums = [0,0,0], target = 1
输出:0
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] nums = {-1, 2, 1, -4}; if (nums.length < 3) { System.out.println("不符合题意的数组大小"); return; } int threeSumClosest = threeSumClosest(nums, 1); System.out.println(threeSumClosest); } /** * 求出最接近目标值target的三数之和 * * @param nums 要传入的数组 * @param target 目标值 * @return 最接近目标值target的三数之和 */ public static int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int ans = nums[0] + nums[1] + nums[2]; for (int i = 0; i < nums.length; i++) { // 前置位置startIndex,后置位置endIndex int startIndex = i + 1, endIndex = nums.length - 1; while (startIndex < endIndex) { int sum = nums[startIndex] + nums[endIndex] + nums[i]; // 更新最接近的值,通过比较,获取到最接近target的值 if (Math.abs(target - sum) < Math.abs(target - ans)) { ans = sum; } // 如果求和值大于目标值,后置位置往前挪 if (sum > target) { endIndex--; } else if (sum < target) { // 如果求和值小于目标值,后置位置往前挪 startIndex++; } else { // 如果等于目标值,直接返回 return ans; } } } return ans; } }
这篇关于LeetCode - 最接近的三数之和的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升