• 16. 3Sum Closest


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

    解析

    
    // three sum closest
    class Solution_16 {
    public:
    	// 三个指针操作O(N^2) test=([0,2,1,-3] 1);([1,1,-1,-1,3]-1)
    	int threeSumClosest(vector<int>& nums, int target) {
    		if (nums.size() < 3)
    		{
    			return 0;
    		}
    
    		int closest_sum = nums[0] + nums[1] + nums[2];
    		sort(nums.begin(), nums.end());
    		for (int first = 0; first < nums.size() - 2; first++)
    		{
    			if (first > 0 && nums[first] == nums[first - 1])
    			{
    				continue;
    			}
    			int second = first + 1;
    			int end = nums.size() - 1;
    			while (second<end)
    			{
    				int temp = nums[first] + nums[second] + nums[end];
    
    				if (abs(closest_sum - target)>abs(temp - target))
    				{
    					closest_sum = temp;
    				}
    				if (temp == target)
    				{
    					return temp;
    				}
    				else if (temp < target)
    				{
    					second++;
    				}
    				else
    				{
    					end--;
    				}
    			}
    		}
    		return closest_sum;
    	}
    
    	// 暴力O(n^3)
    	int threeSumClosest_1(vector<int> &num, int target)
    	{
    		int res = num[0] + num[1] + num[2];
    		for (int i = 0; i < num.size() - 2; i++){
    			for (int j = i + 1; j < num.size() - 1; j++){
    				for (int t = j + 1; t < num.size(); t++){
    					int tem = num[i] + num[j] + num[t];
    					if (abs(target - tem) < abs(target - res))
    						res = tem;
    					if (res == target)
    						return res;
    				}
    			}
    		}
    		return res;
    	}
    };
    
    
    

    题目来源

  • 相关阅读:
    [BZOJ4755][JSOI2016]扭动的回文串(manacher+Hash)
    十二省联考2019部分题解
    [BZOJ2959]长跑(LCT+并查集)
    [BZOJ4541][HNOI2016]矿区(平面图转对偶图)
    笛卡尔树
    [CF896C]Willem, Chtholly and Seniorious(珂朵莉树)
    [BZOJ4349]最小树形图
    [BZOJ1858][SCOI2010]序列操作(线段树)
    [PA2014]Parking
    [PA2014]Budowa
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8322222.html
Copyright © 2020-2023  润新知