leetcode 16 3Sum Closet
来源:互联网 发布:淘宝充值软件利润 编辑:程序博客网 时间:2024/06/05 01:54
3Sum Closest
Total Accepted: 53147 Total Submissions: 195388 Difficulty: MediumGiven 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).
这道题的思路和之前的4Sum的思路一致,先把所有数增序排序,然后用三个指针,第一个指针从头到尾走形成第一层循环,第二个指针从第一个指针的下一个开始往后走,第三个指针从最后一个开始往前走,当第二个指针和第三个指针相遇时,就穷尽了在第一个指针固定的情况下,第二个数和第三个数的可能产生最接近值的组合情况,采用的策略是如果第二个数和第三个数相加的和大于target,则第三个指针往前走一个,因为之前已经按增序排序,所以第三个指针指向一个比之前小的值,如果第二个数和第三个数相加的和小于target,则第二个指针往后走一个,所以第二个指针指向一个比之前大的值。所以这个算法实际上是一个双重循环。
下面是完整程序代码:
#include <iostream>#include <stdlib.h>using namespace std;int abs(int n){ return n>0?n:-1*n;}int cmp(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); /*for(int i = 0; i < numsSize; i++) { cout<<nums[i]<<" "; }*/ int optimal, difference = 10000000, p, q, tmp; for(int i = 0; i < numsSize - 2; i++) { p = i + 1; q = numsSize - 1; while(p < q) { tmp = nums[i] + nums[p] + nums[q] - target; if(abs(tmp) < difference) { difference = abs(tmp); optimal = nums[i] + nums[p] + nums[q]; } if(tmp < 0) p++; else if(tmp == 0) return optimal; else q--; } } return optimal;}int main(){ int numsSize, *nums, target; cout<<"Input the size of numbers:"<<endl; cin>>numsSize; nums = (int*)malloc(sizeof(int) * numsSize); for(int i = 0; i < numsSize; i++) { cin>>nums[i]; } cout<<"Input the target:"<<endl; cin>>target; cout<<endl<<threeSumClosest(nums, numsSize, target)<<endl; }
- leetcode 16 3Sum Closet
- leetcode-16 3Sum Closet
- LeetCode 16 3Sum Closet
- leetcode:3sum closet
- Leetcode 3Sum Closet
- 3Sum closet | LeetCode
- FTPrep: 16, 3Sum Closet
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- 3Sum Closet
- 3 Sum Closet
- 3sum closet
- 3Sum Closet
- 3sum closet
- 15. 3Sum && 16 sum closet && 18 4sum
- 刷题的日常[Leetcode]——16)3 Sum Closet
- 3sum、3Sum closet、 4sum
- 类型系列题目:1. Two Sum 15,3 sum ,16 3sum closet, 18 4sum, 454 4Sum II
- Three Sum Closet
- java学习_IO(2)
- A840S黑砖修复过程(2013-05-22修改)
- matlab中运用项目思维分析问题并解决问题
- USACO 2.3 Money Systems (DP 动态规划 + 空间优化)
- 深入理解javascript原型链
- leetcode 16 3Sum Closet
- 安卓控件使用系列24:Gallery画廊控件的使用方法
- HighCharts坐标轴Y轴倒过来画图
- java nio 高级
- 组合数与错排数求解方法探析
- HighCharts设置多个Y轴 Y轴位置
- 非静态成员引用必须与特定对象相对
- (lamphc0)配置服务器及服务器端的开发环境=>长期更新
- Java的类引用的思索