• 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;
    	}
    };
    
    
    

    题目来源

  • 相关阅读:
    python setup.py install 失败
    Python xlsx 读取
    Java ArrayList Sort
    java console ( mac osx ) 命令行编码
    Lucene Query Term Weighting
    Fast Intro To Java Programming (2)
    随感 20150512
    循环数组中找查找某个数值
    数字内组合得到下一个比该数大的数
    android activity空指针异常解决问题解决
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8322222.html
Copyright © 2020-2023  润新知