OJ address
Leetcode website : 16. 3Sum Closest
Description
Given an array nums of n integers 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.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Solution in C
int (const void *a, const void *b) { return *(int *)a - *(int *)b; } int threeSumClosest (int * nums, int numsSize, int target) { qsort(nums, numsSize, sizeof (int ), cmp); if (numsSize < 3 ) { return 0 ; } int pre = INT_MAX; int sum = 0 ; for (int i=0 ;i<numsSize-2 ;++i) { if (i>0 && nums[i] == nums[i-1 ]) continue ; if (nums[i] > target && pre != INT_MAX) break ; for (int j=i+1 ;j<numsSize-1 ;++j) { int index = numsSize-1 ; if (index <= j) break ; if (j>i+1 && nums[j] == nums[j-1 ]) continue ; int res = target - nums[i] - nums[j]; if (res == nums[index]) { return target; } else if (res < nums[index]) { if (abs (res-nums[index]) == pre) { if (nums[i]+nums[j]+nums[index] > sum) sum = nums[i]+nums[j]+nums[index]; } if (abs (res-nums[index]) < pre) { pre = abs (res-nums[index]); sum = nums[i]+nums[j]+nums[index]; } --index; while (index > j) { int res = target - nums[i] - nums[j]; if (res == nums[index]) { return target; } else if (res < nums[index]){ if (abs (res-nums[index]) == pre) { if (nums[i]+nums[j]+nums[index] > sum) sum = nums[i]+nums[j]+nums[index]; } if (abs (res-nums[index]) < pre) { pre = abs (res-nums[index]); sum = nums[i]+nums[j]+nums[index]; } --index; } else { if (abs (res-nums[index]) == pre) { if (nums[i]+nums[j]+nums[index] > sum) sum = nums[i]+nums[j]+nums[index]; } if (abs (res-nums[index]) < pre) { pre = abs (res-nums[index]); sum = nums[i]+nums[j]+nums[index]; } break ; } } --index; } else { if (abs (res-nums[index]) == pre) { if (nums[i]+nums[j]+nums[index] > sum) sum = nums[i]+nums[j]+nums[index]; } if (abs (res-nums[index]) < pre) { pre = abs (res-nums[index]); sum = nums[i]+nums[j]+nums[index]; } } } } return sum; }
My Idea
算出三个数值和target最相近的值,如果target为0,如果最近的数字有1,-1,那答案为1,也就是说最近的两个值取大于target值的解。
近期评论