Leetcode 3Sum Closest problem solution in C programming

In the Leetcode 3Sum Closest problem solution in C programming Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Leetcode 3Sum Closest problem solution in C programming

int comp (const void * elem1, const void * elem2) 
{
    int f = *((int*)elem1);
    int s = *((int*)elem2);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}

int threeSumClosest(int* nums, int numsSize, int target)
{
    qsort(nums, numsSize, sizeof(int), comp);
    int ret = nums[0] + nums[1] + nums[2];
    int sum;
    if (numsSize == 3)
        return (ret);
    for (int i = 0; i < numsSize - 2; ++i)
    {
        int j = i + 1;
        int k = numsSize - 1;
        while (j < k)
        {
            sum = nums[i] + nums[j] + nums[k];
            if (abs(target - ret) > abs(target - sum))
            {
                ret = sum;
                if (ret == target)
                    return ret;
            }
            sum > target ? k-- : j++;
        }
    }
    return ret;
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *