LeetCode 16. 最接近的三数之和
2019-04-22 16:09
417 查看
版权声明:本文为 renhq 原创文章,转载请注明出处: https://blog.csdn.net/qq_37499840/article/details/89453557
github:https://github.com/Renhongqiang/LeetCode
给定一个包括 n 个整数的数组
nums和 一个目标值
target。找出
nums中的三个整数,使得它们的和与
target最接近。返回这三个数的和。假定每组输入只存在唯一答案。
[code]例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
思路:
三数之和:https://blog.csdn.net/qq_37499840/article/details/89453033
类比三数之和:依然排序,遍历nums,每次遍历为 nums[i] 设置 l=i+1、r=nums.length-1,l++、r--,使用rst记录目前最接近target的值,与遍历到的 nums[i] + nums[l] + nums[r] 比较,取二者中最接近 target 的值,然后判断 temp(三数和) 与 target 的大小关系,temp < target 则 l 右移,因为升序排序,否则 r 左移,如果相等则直接返回target。
[code]class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int rst = nums[0] + nums[1] + nums[2]; int l,r,temp; for(int i = 0; i < nums.length - 2; i++) { l = i + 1; r = nums.length - 1; while(l < r) { temp = nums[i] + nums[l] + nums[r]; if(Math.abs(target - rst) > Math.abs(target - temp)) { rst = temp; } if(temp > target) r--; else if(temp < target) l++; else return target; } } return rst; } }
相关文章推荐
- LeetCode- 16. 最接近的三数之和 (Medium)python和c++实现
- leetcode 腾讯精选练习(50 题)16.最接近的三数之和
- 【PHP解法==LeetCode查找类型问题2(N数之和)】15.三数之和 && 16.最接近的三数之和 && 18.四数之和 && 454.四数相加II
- leetcode16---最接近的三数之和
- 【leetcode每日一题】【2019-05-27】16. 最接近的三数之和
- LeetCode题解(python)-16. 最接近的三数之和
- LeetCode16.最接近的三数之和
- Leetcode刷题38-16.最接近的三数之和(C++)
- 16. 最接近的三数之和(leetcode Java语言)
- leetcode 16. 最接近的三数之和(Java版)
- LeetCode 16 C++ 最接近的三数之和
- 【Leetcode】16. 最接近的三数之和
- LeetCode 16. 最接近的三数之和
- leetcode 16 最接近的三数之和
- LeetCode16-最接近的三数之和
- LeetCode 16 最接近的三数之和
- leetcode 16 最接近的三数之和
- [LeetCode] 16. 3Sum Closest 最接近的三数之和 @python
- Leetcode=最接近的三数之和
- LeetCode-16 最近的三数之和