[LeetCode] 3Sum Closest

简介: This problem is very similar to 3Sum. You only need to maintain a variable for the sum that is closet to target.

This problem is very similar to 3Sum. You only need to maintain a variable for the sum that is closet to target. Also, some corner cases need to be handled; for example, nums does not have more than 2 elements.

The code is as follows, which is quite self-explanatory.

 1     int threeSumClosest(vector<int>& nums, int target) {
 2         sort(nums.begin(), nums.end());
 3         while (nums.size() <= 2)
 4             return accumulate(nums.begin(), nums.end(), 0);
 5         int ans = nums[0] + nums[1] + nums[2];
 6         for (int i = 0; i < nums.size() - 2; i++) {
 7             int left = i + 1, right = nums.size() - 1;
 8             while (left < right) {
 9                 int temp = nums[i] + nums[left] + nums[right];
10                 if (abs(temp - target) < abs(ans - target))
11                     ans = temp;
12                 if (temp == target) return ans;
13                 if (temp > target) right--;
14                 else left++;
15             }
16         }
17         return ans;
18     }
目录
相关文章
|
算法 机器学习/深度学习
|
算法 编译器
LeetCode:658. Find K Closest Elements程序分析
好久没有练习算法了,以此纪研究生以来第一次练习算法题。 原题链接:https://leetcode.com/problems/find-k-closest-elements/description/ 题目描述:大概意思是给定一个数组[1,2,3,4,5]和两个常数k,x然后在数组中找到与x最近的的k个元素,找到后的元素依旧按照升序排列。
1724 0
LeetCode - 16. 3Sum Closest
16. 3Sum Closest  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个整数序列和一个目标数,在序列中找出三个数,使得这三个数的和与目标数的差最小.
691 0
|
C++
[LeetCode] Closest Binary Search Tree Value II
Problem Description: Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
1184 0
|
C++
[LeetCode] Closest Binary Search Tree Value
Problem Description: Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
904 0
|
2月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行