leetcode16.3Sum Closest
题外话
鉴于这一题的核心思路和leetcode15的思路相同,可以先写一下15题并参考一下我之前的一篇博客
题目要求
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
1 | For example, given array S = {-1 2 1 -4}, and target = 1. |
翻译过来就是,假设一个有n的元素的整数数组S,从S中找到三个值,这三个值的距离输入的目标值最近。返回这三个值的和。
思路一:三指针
这里的思路和leetcode15是一样的,就是用三个指针获得三个值并计算他们的和。不同的是和当前的最小距离比较,代码如下
1 | public int threeSumClosest(int[] nums, int target) { |
思路二:hashmap等
同leetcode15,请直接参考我的博客