[LeetCode] 3Sum Closest

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

 

Hide Tags
  Array Two Pointers
 
  这是一道讨论的题目,方法有很多种,最直接的方法是 3层for 循环遍历。
  第二种方法是 外两次for 循环,第三个数通过 二分查找,时间 是 O(nn logn)
      第三种方法,时间是O(nn),外层是for循环,内层是 数组首尾指针向中间靠拢,搜索最优结果。
 
#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;



class Solution {

public:

    int threeSumClosest(vector<int> &num, int target) {

        if(num.size()<4){

            int retNum=0;

            for(int i=0;i<num.size();i++)

                retNum += num[i];

            return retNum;

        }

        vector<int> tmpnum = num;

        sort(tmpnum.begin(),tmpnum.end());

//        for(int i=0;i<tmpnum.size();i++)

//            cout<<tmpnum[i]<<" ";

//        cout<<endl;

        int retNum = tmpnum[0]+tmpnum[1]+tmpnum[2];

        for(int outIdx = 0;outIdx<tmpnum.size();outIdx++){

            int intarget = target-tmpnum[outIdx];

            for(int inleft=0,inright=num.size()-1;inleft<inright;){

                if(inleft==outIdx){

                    inleft++;   continue;

                }

                if(inright==outIdx){

                    inright--;  continue;

                }

//                cout<<tmpnum[inleft]<<" "<<tmpnum[inright]<<endl;

                if(abs(tmpnum[inleft]+tmpnum[inright] + tmpnum[outIdx]-target)<abs(retNum-target) )

                    retNum = tmpnum[inleft]+tmpnum[inright] + tmpnum[outIdx];



                if(tmpnum[inleft]+tmpnum[inright]<intarget)

                    inleft++;

                else if(tmpnum[inleft]+tmpnum[inright]>intarget)

                    inright--;

                else

                    return retNum;

            }

        }

        return retNum;

    }

};



int main()

{

    vector<int > num{1,1,-1,-1,3};

    Solution sol;

    cout<<sol.threeSumClosest(num,-1)<<endl;

    return 0;

}

 

你可能感兴趣的:(LeetCode)