美文网首页
16. 最接近的三数之和 难度:中等

16. 最接近的三数之和 难度:中等

作者: vincewi | 来源:发表于2021-03-04 13:06 被阅读0次

题目描述:

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例:

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

提示

  • 3 <= nums.length <= 10^3
  • -10^3 <= nums[i] <= 10^3
  • -10^4 <= target <= 10^4

思路

快排 + 双指针

代码示例:

int compare (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}
int threeSumClosest(int* nums, int numsSize, int target){
    qsort(nums, numsSize, sizeof(int), compare);
    int ret = nums[0] + nums[1] + nums[2];
    int i;
    for(i = 0; i < numsSize - 2; i ++) {
        if(i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        int left = i + 1;
        int right = numsSize - 1;
        while(left < right) {
            int sum = nums[i] + nums[left] + nums[right];
            if(sum == target) {
                return target;
            } else if(sum < target) {
                left ++;
            } else {
                right --;
            }
            if(abs(sum - target) < abs(ret - target)) {
                ret = sum;
            }
        }
    }
    return ret;
}

相关文章

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

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

  • 16. 最接近的三数之和 难度:中等

    题目描述: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,...

  • 力扣每日一题:16.最接近的三数之和 双指针解法

    16.最接近的三数之和 https://leetcode-cn.com/problems/3sum-closest...

  • 16.最接近的三数之和

    16.最接近的三数之和 题目链接:https://leetcode-cn.com/problems/3sum-cl...

  • LeetCode-15 三数之和

    题目:15. 三数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第15题三数之和,这是一道中等题。像...

  • 16. 三数之和最接近

    题目 给定一个整数数组 nums 和一个目标数 target,在 nums 中找出三个数,要求其和与 targe...

  • algrithrom

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

  • 16. 最接近的三数之和

    一、题目原型: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整...

  • 16.最接近的三数之和

    题目给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们...

  • 16. 最接近的三数之和

    知乎ID: 码蹄疾码蹄疾,毕业于哈尔滨工业大学。小米广告第三代广告引擎的设计者、开发者;负责小米应用商店、日历、开...

网友评论

      本文标题:16. 最接近的三数之和 难度:中等

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