3Sum Closest
来源:互联网 发布:java基础知识体系结构 编辑:程序博客网 时间:2024/05/20 15:38
本文转载自:http://blog.csdn.net/doc_sgl/article/details/12461893
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).
- int threeSumClosest(vector<int> &num, int target) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- int numlen = num.size();
- if(numlen<3)return -1;
- sort(num.begin(),num.end());
- int minGap = num[0]+num[1]+num[2]-target;
- for(int i = 0; i <= numlen-3; i++)
- {
- int begin = i+ 1;
- int end = numlen-1;
- while(begin < end)
- {
- int curGap = num[i]+num[begin]+num[end]-target;
- if(curGap == 0) return target;
- if(abs(curGap) < abs(minGap)) minGap = curGap;
- if(curGap < 0) begin++;
- else end--;
- }
- }
- return target+minGap;
- }
0 0
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- LeetCode: 3 Sum Closest
- 3Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- leetcode002:3sum closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- [LeetCode] 3Sum Closest
- const_interator的用法
- Java NIO 系列教程
- Android背景平铺
- Anagram --- 哈希算法
- 蓝桥杯试题
- 3Sum Closest
- Java NIO系列教程(一) Java NIO 概述
- Android 编程下 Touch 事件的分发和消费机制
- AWK
- java里面的synchronized关键字详解
- mysql同步字符集故障处理
- 文件上传三剑客(二)-后台数据库存储
- 开灯问题
- 被占用的COM释放