Fork me on GitHub

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


题目来源

posted @   ranjiewen  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 上周热点回顾(1.20-1.26)
· 【译】.NET 升级助手现在支持升级到集中式包管理
历史上的今天:
2017-01-20 2016回顾2017展望
点击右上角即可分享
微信分享提示