lintcode 最接近的三数之和

作者: yzawyx0220 | 来源:发表于2017-01-04 15:37 被阅读98次

给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。
注意事项
只需要返回三元组之和,无需返回三元组本身
样例
例如 S = [-1, 2, 1, -4] and target = 1. 和最接近 1 的三元组是 -1 + 2 + 1 = 2.
题目链接:http://www.lintcode.com/zh-cn/problem/3sum-closest/#

首先对数组进行排序,如果第一个数就比目标值的三分之一大,那么久返回前三个数的和,如果最后三个数比目标值的三分之一小,就返回最后三个数的和。如果不是以上两种情况,遍历数组。
这里也是有三个指针,如果第一个指针(i)指向的数比目标值的三分之一小,直接跳过(第一个指针指向的是三个数中最大的),如果和下一个数一样,也跳过。然后就是把三个数的和和target进行比较,分为两种情况,遇到重复的数同样是跳过。

class Solution {
public:    
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target: An integer
     * @return: return the sum of the three integers, the sum closest target.
     */
    int threeSumClosest(vector<int> nums, int target) {
        // write your code here
        sort(nums.begin(),nums.end());
        if (nums[0] >= target/3) return nums[0] + nums[1] + nums[2];
        if (nums[nums.size()-1] <= target/3) return nums[nums.size()-1] + nums[nums.size()-2] + nums[nums.size()-3];
        int res;
        int d = INT_MAX;
        for (int i = 2;i < nums.size();i++) {
            if (nums[i] < target/3 || i+1 < nums.size() && nums[i] == nums[i+1]) continue;
            for (int j = 0,k = i - 1,sum = nums[j] + nums[k],temp = target - nums[i];j < k;sum = nums[j] + nums[k]) {
                if (sum < temp || j > 0 && nums[j] == nums[j-1]) {
                    if (temp - sum < d) {
                        d = temp -sum;
                        res = sum + nums[i];
                    }
                    j++;
                }
                else if (sum > temp || k+1 < i && nums[k] == nums[k+1]) {
                    if (sum - temp < d) {
                        d = sum - temp;
                        res = sum + nums[i];
                    }
                    k--;
                }
                else return target;
            }
        }
        return res;
    }
};

相关文章

  • lintcode 最接近的三数之和

    给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。注意事项只需...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • 刷Lintcode:最接近的三数之和

    给一个包含n个整数的数组S, 找到和与给定整数target最接近的三元组,返回这三个数的和。 样例 例如S=[-1...

  • LeetCode-16 最接近的三数之和

    题目:16. 最接近的三数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第16题最接近的三数之和,这...

  • 双指针总结

    左右指针 主要解决数组中的问题:如二分查找 盛最多水的容器 三数之和 四数之和 最接近三数之和 快慢指针 主要解决...

  • lintcode 三数之和

    给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。注意...

  • LeetCode练习day1-数组相关

    LeetCode16 最接近的三数之和 相似题目:LeetCode15 三数之和 题目详情 给你一个长度为 n 的...

  • LintCode三数之和系列问题

    三数之和 LintCode57 三数之和解题思路:先对数组排序,然后开始遍历,对于数组中的每一个元素,用两指针往中...

  • 最接近的三数之和

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/3sum...

  • 最接近的三数之和

    题目 思路 题解

网友评论

    本文标题:lintcode 最接近的三数之和

    本文链接:https://www.haomeiwen.com/subject/mwgovttx.html