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)遍历数组,用一个for循环控制作为外循环,下标从小到大进行遍历,因为需要3个数,所以用外循环的这个下标对应的数组值作为base,然后再 初始化一个begin作为base的下一位置,end作为数组末尾,三者相加得到sum,若是value=sum-target(目标值)更小则保存sum的值,并且若value<0 则begin++,若value>o则end--,若是value=0,则返回target;看代码:
class Solution { public: int threeSumClosest(vector<int>& nums, int target); int findClosest(vector<int>& nums, int base, int end, int target); private: int result, finalResult, gap = 99999999, gap1 = 99999999; }; int Solution::threeSumClosest(vector<int>& nums, int target){ //int result,gap=99999999; sort(nums.begin(), nums.end()); int len = nums.size(); for (int i = 0; i < nums.size() - 2; i++) { //cout << "before" << endl; int res1 = findClosest(nums, i, len - 1, target); if (res1 < gap1) gap1 = res1; finalResult = result; } // cout << "over" << endl; // return gap1; return finalResult; } int Solution::findClosest(vector<int>& nums, int base, int end, int target){ //cout << "executing" << endl; int begin = base + 1; while (begin < end){ int value = nums[base] + nums[begin] + nums[end] - target; int temp = abs(nums[base] + nums[begin] + nums[end] - target); if (temp <= gap){ // int s = nums[base], s2 = nums[begin], s3 = nums[end]; gap = abs(nums[base] + nums[begin] + nums[end] - target); result = nums[base] + nums[begin] + nums[end]; if (value == 0) return 0; else if (value>0) end--; else if (value < 0) begin++; } else { if (value>0) end--; else begin++; // return gap; } } return gap; }
时间: 2024-12-30 08:35:55