3Sum Closest
2015-08-26 10:32
169 查看
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.
思路:这道题目的做法与3Sum的做法大致相同,只不过需要增加一个标记来记录每一次比较的最接近的值即可,代码如下:
思路:这道题目的做法与3Sum的做法大致相同,只不过需要增加一个标记来记录每一次比较的最接近的值即可,代码如下:
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int len = nums.size(), i, j, k, closest = 0, delta = 2147483647; if(len == 3) return nums[0] + nums[1] +nums[2]; sort(nums.begin(), nums.end()); for(i = 0; i < len - 2; ++i){ if(i > 0 && nums[i] == nums[i - 1]) continue; j = i + 1; k = len - 1; while(j < k){ if(j > i + 1 && nums[j] == nums[j - 1]){ j++; continue; } if(k < len - 1 && nums[k] == nums[k + 1]){ k--; continue; } int sum = nums[i] + nums[j] + nums[k]; int tmpDelta = abs(sum-target); if(delta > tmpDelta){ delta = tmpDelta; closest = sum; } if(sum < target) j ++; else if(sum > target) k --; else{ return sum; } } } return closest; } };
相关文章推荐
- 执行上下文
- MySQL(一)之通用二进制格式安装MySQL及数据库基本概念
- POJ 2594--Treasure Exploration【二分图 && 最小路径覆盖 && 点可以重复走 && 传递闭包】
- CAN 报文信号编码规则 intel & motorola
- zato集群部署
- POJ 1035 代码+具体的目光
- iOS GPUImage的简单说明
- 滚动侦测scrollspy
- SQLSTATE[42000]: Syntax error or access violation: 1055 'kf_local.g.group_name' isn't in GROUP BY
- SQLite这么娇小可爱,不多了解点都不行啊
- reveal
- HTTP协议解析
- size_t与ssize_t
- Leetcode: Summary Ranges
- Swift 属性值监测
- tomcat web.xml配置详解
- linux挂载windows共享文件夹的方法
- Java——IO流
- getsockname()(cp:http://wiki.gimoo.net/view/11495.html)
- Android 集成支付宝SDK实现快捷支付--详解