Leetcode10 threesumclosest

来源:互联网 发布:怎么拷贝oracle数据库 编辑:程序博客网 时间:2024/06/06 08:44

1、题目描述
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).

2、解题思路
首先由target开始按照上一篇博文中的方法求是否存在三个元素的和等于target,不存在的话在继续使用接近目标值的数更新目标值target,代码中利用tar=target+/-m来实现。
3、实现代码

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        auto n=nums.size();        for(int i =0 ; i< n-1; ++i) {             for(int j = 0; j < n-i-1; ++j) {                  if(nums[j] > nums[j+1])                  {                      int tmp = nums[j] ; nums[j] = nums[j+1] ;  nums[j+1] = tmp;                 }              }        }//bubblesort of nums including resorting of index        int tar=target;         int  m=0;        int flag=0;        do{            for(tar=target-m;tar<=(target+m);tar+=2*m){                for(int i=0;i<n/2;i++){                    int j=i+1,k=n-1;                    int tar1=tar=nums[i];                    while(j<k){                        int sum=nums[j]+nums[k];                        if(sum<tar1)                            j++;                        else if(sum>tar1)                            k--;                        else{                            return tar;                        }                    }                }             }        }while(++m);    }};
0 0
原创粉丝点击