1. 程式人生 > >【LeetCode】3Sum Closest

【LeetCode】3Sum Closest

get 冒泡 else if body family void class else ray

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;
}

  

 

【LeetCode】3Sum Closest