LeetCode3Sum Closest

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode3Sum Closest相关的知识,希望对你有一定的参考价值。

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.

    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).
/**
 * 冒泡排序
 */
void BubleSort(int *arr,int len)
{
    int k = 0,i = 0,j = 0;
    for(j = 0;j < len;j++)
    {
        for(i = 0;i < len-j-1;i++)
        {
            if(arr[i] > arr[i+1])
            {
                k = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = k;
            }
        }
    }
}

int threeSumClosest(int* nums, int numsSize, int target) {
    BubleSort(nums,numsSize);
    
    int left = 0,mid = 0,right = 0;
    int minTarget = nums[0]+nums[1]+nums[2];
    
    for(left = 0;left < numsSize-2;left++){
        mid = left + 1;
        right = numsSize-1;
        while(mid < right) {
            int num = nums[left] + nums[mid] + nums[right];
            if(abs(target-minTarget) > abs(target-num))
                minTarget = num;
            
            if(num == target) return num;
            else if(num > target) {
                right--;
            }
            else mid++;
        }
    }
    
    return minTarget;
}

  

 

以上是关于LeetCode3Sum Closest的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode3Sum Closest 解题报告

Leetcode3Sum

使用closest替换parent

UVA - 10245 The Closest Pair Problem

Closest Common Ancestors (Lca,tarjan)

Codeforces 522D Closest Equals