首页 > 学院 > 开发设计 > 正文

3Sum Closest问题及解法

2019-11-06 06:09:26
字体:
来源:转载
供稿:网友

问题描述:

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;    }};问题难度不大,有疑问的话欢迎交流~~


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表