Leetcodes Solutions 16 3Sum closest

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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).

思路1

遍歷的過程類似3Sum,只是要找的目標是一個給定的值,而且返回的是三個數求和後,離給定值最近的值。

class Solution{public: int threeSumClosest(vector<int> &num, int target){ vector<int> v(num.begin(), num.end()); //not to disturb the original array int n = 0; int ans = 0; int sum; sort(v.begin(), v.end()); //if less than 3 elements then return their sum while(v.size() <= 3) return accumulate(v.begin(), v.end(), 0); n = v.size(); ans = v[0] + v[1] + v[2]; for(int i = 0; i < n - 2; i++){ int j = i + 1; int k = n - 1; while(j < k){ sum = v[i] + v[j] + v[k]; if(abs(target - ans) > abs(target - sum)){ //ans到target的距離大於sum到target的距離 ans = sum; if(ans == target) return ans; } (sum > target) ? k-- : j++; } } return ans; }};

推薦閱讀:

貢獻一個最新版的OpenGrok Docker容器
python多線程之從Thread類繼承
DevDocs, windows下Dash的替代品,括弧笑
偽·從零開始學Python - 2.1 面向過程的程序設計簡述

TAG:編程 | 數據結構 | 演算法 |