問題描述:
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.將數組升序排序
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;    }};問題難度不大,有疑問的話歡迎交流~~
新聞熱點
疑難解答