首页 > 代码库 > [LeetCode]3 Sum Closet
[LeetCode]3 Sum Closet
// 3SumClosest.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <vector>#include<cstdlib>#include <iostream>#include <algorithm>using namespace std;class Solution {public: int threeSumClosest(vector<int> &num, int target) { int closet = 999999; sort(num.begin(),num.end()); for (int i = 0; i < num.size()-2; i++) { if (i>0 && num[i] == num[i - 1]) continue; int p1 = i + 1, p2 = num.size() - 1; while (p1 < p2) { if (p1>i + 1 && num[p1] == num[p1 - 1]) { p1++; continue; } if (p2 < num.size() - 1 && num[p2] == num[p2 + 1]) { p2--; continue; } if (p1>p2) break; int sum = num[i] + num[p1] + num[p2]; if (sum == target) { p2--; closet = target; } else if (sum<target) { p1++; if (abs(sum - target) < abs(closet - target)) { closet = sum; } } else { p2--; if (abs(sum - target) < abs(closet - target)) { closet = sum; } } } } return closet; }};int _tmain(int argc, _TCHAR* argv[]){ Solution ss; vector<int>test; test.push_back(1); test.push_back(1); test.push_back(1); test.push_back(0); //test.push_back(-4); int sum = ss.threeSumClosest(test,100); cout << sum << endl; system("pause"); return 0;}
[LeetCode]3 Sum Closet
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。