zoukankan      html  css  js  c++  java
  • 16. 最接近的三数之和

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。

    返回这三个数的和。假定每组输入只存在唯一答案。

    例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

    与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

    /*
    解题思路:
    最接近于给定值的值,即我们要保证当前三数和跟给定值之间的差的绝对值最小,
    所以我们需要定义一个变量 temp2用来记录差的绝对值,然后我们还是要先将数组排个序,
    然后开始遍历数组。
    */
    
    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    class Solution {
    public:
    	int threeSumClosest(vector<int>& nums, int target)
    	{
    		sort(nums.begin(), nums.end());
    		int len = nums.size();
    		int result;
    		int temp1, temp2;
    		int min = abs(nums[0] + nums[1] + nums[2] - target);
    		for (int i = 0; i < len - 2; i++)
    		{
    			for (int j = i + 1; j < len - 1; j++)
    			{
    				for (int k = j + 1; k < len; k++)
    				{
    					temp1 = nums[i] + nums[j] + nums[k];
    					temp2 = abs(temp1 - target);
    					if (temp2 <= min)
    					{
    						min = temp2;
    						result = temp1;
    					}
    				}
    			}
    		}
    		return result;
    	}
    };
    int main(){
    	vector<int>nums;
    	int target;
    	cin >> target;
    	int a[1000];
    	int i = 0;
    	int x;
    	while (cin >> a[i])
    	{
    		x = cin.get();
    		if (x == '
    ')
    			break;
    		nums.push_back(a[i]);
    		++i;
    	}	
    	cout << Solution().threeSumClosest(nums, target) << endl;
    	system("pause");
    	return 0;
    
    }
    

      

      

  • 相关阅读:
    第四章——64位软件逆向技术-基本语法(上)
    第三章——静态分析技术-IDA的简单操作
    第二章——动态分析技术-OD常见问题
    工厂模式及其抽象工厂
    设计模式-原则
    设计模式-简单工厂模式
    设计模式-桥接模式
    设计模式
    Linux下安装软件心得
    光驱挂载和下载
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/11402107.html
Copyright © 2011-2022 走看看