3Sum Closest問題及解法
阿新 • • 發佈:2019-01-04
問題描述:
Given an arraySofnintegers, find three integers inSsuch 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.將陣列升序排序
2.設定兩個指標 front 和 back 分別指向陣列的前段和後端
3.先選取好第一個元素,然後遍歷第二和第三個元素,將三者的和與目標值target作比較,選取距離較近的
過程詳見程式碼:
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int res = 0; int dist = INT_MAX; sort(nums.begin(), nums.end());//排序 for(int i = 0; i < nums.size(); i++) { int front = i + 1; int back = nums.size() - 1; while(front < back) { int sum = nums[i] + nums[front] + nums[back]; if(sum < target) { int temp = target - sum; if(temp < dist) { dist = temp; res = sum; } front++; } else if(sum > target) { int temp = sum - target; if(temp < dist) { dist = temp; res = sum; } back--; } else { return target; } } } return res; } };
問題難度不大,有疑問的話歡迎交流~~