3 Sum Closet

题目

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.

给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。

https://leetcode.com/problems/3sum-closest/description/

样例

For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

例如 S = [-1, 2, 1, -4] and target = 1. 和最接近 1 的三元组是 -1 + 2 + 1 = 2.

解题思路

这道题的仍然是使用两个指针 Two Pointers的方法来解决,解题思路和3 Sum这道题相似,这里的时间复杂度仍然是O(n^2)。

分别使用3个指针来指向当前元素、下一个元素和最后一个元素。如果结果Sum是小于目标值的,我们就将下一个元素接着向数组右侧遍历;如果结果Sum是大于目标值的,那么我们将最后一个元素向左侧遍历。
并且,每次我们都比较当前结果和目标值的差值,如果这个差值小于上一次的结果,将上一次的结果替换,否则的话,继续遍历。

具体代码如下:

public int threeSumClosest(int[] nums, int target) {
        int res = nums[0] + nums[1] + nums[nums.length - 1];
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target) {
                    res = sum;
                    return res;
                } else if (sum < target) {
                    left++;
                } else {
                    right--;
                }
                if (Math.abs(sum - target) < Math.abs(res - target)) {
                     res = sum;
                }
            }
        }
        return res;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • Two Sum 题目: Given an array of integers, find two numbers ...
    lyoungzzz阅读 406评论 0 0
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,891评论 0 23
  • 到这里,在ZEALANDIA的时间就还剩下这两周了,五点上班的悲催生活随着先我们前一周入职的小伙伴的即将离开也快要...
    cora的生活手册阅读 413评论 0 1
  • 不知道是不是所有十七八岁的孩子们都像我一样,明明应该是积极向上但大多数时间都是处于迷茫慌张的状态。 十七八岁的...
    哗啦啦噜阅读 119评论 0 0