LeetCode : 3Sum Closest
来源:互联网 发布:a星算法怎么算线性袋鼠 编辑:程序博客网 时间:2024/04/28 06:20
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).
class Solution {public: int threeSumClosest(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = num.size(); if(n ==0 )return 0; vector<int> tuple(3); sort(num.begin(), num.end()); int min = abs(num[0] + num[1] + num[2] - target); tuple[0] = num[0]; tuple[1] = num[1]; tuple[2] = num[2]; int val = num[0] - 1; for(int i = 0 ;i < n - 2; ++i){ int j = i + 1; int k = n-1; if(num[i] == val) continue; val = num[i]; while(j < k ){ int temp = abs(num[i] + num[j] + num[k] - target); if(temp < min){ tuple[0] = num[i]; tuple[1] = num[j]; tuple[2] = num[k]; min = temp; } if(temp == 0){ break; } if(num[i] + num[j] + num[k] > target){ --k; } else{ ++j; } } } return tuple[0] + tuple[1] + tuple[2]; }};
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- poj 1035 Spell checker
- Toolbox中的dissolve工具以及与排序工具的组合使用
- Ubuntu下file not found + GRUB rescue肿么办?--由windows下分区调整引起的
- .vimrc
- ORACLE DUAL表详解
- LeetCode : 3Sum Closest
- unix系统编程小结(二)------文件和目录
- JDBC连接数据库
- range-----selection
- eclipse快捷键
- DebugInfoFIlter -- DirectShow调试工具
- 用PyOpenGL叩开3D的心扉——OpenGL全解析
- Android的按钮单击事件及监听器的实现方式
- poj 2406字符串最小环节的应用