LeetCode-016 3Sum Closest
来源:互联网 发布:衣服软件 编辑:程序博客网 时间:2024/05/20 07:53
Description
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.
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).
Analyse
这道题跟上一道题很像,解法也差不多,也是排序,选一个数,然后前后往中间找出两个数,使得他们之和最接近目标值。
Code
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { if (nums.size()<3) return 0; int close=INT_MAX; int ans; sort(nums.begin(),nums.end()); for (int i=0;i<nums.size()-2;i++) { int p=i+1,q=nums.size()-1; while (p<q) { int sum=nums[i]+nums[p]+nums[q]; if (sum<target) { if (target-sum<close) { close=target-sum; ans=sum; } p++; } else { if (sum>target) { if (sum-target<close) { close=sum-target; ans=sum; } q--; } else { return sum; } } } } return ans; }};
阅读全文
0 0
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- [LeetCode]016-3Sum-Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode-016 3Sum Closest
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- Windows程序设计:边框绘制函数
- [BZOJ]3495 Riddle 2-Sat 前缀和优化
- PAT1042. 字符统计(20) C++
- 2017/12/8
- Xerces-C++解析XML
- LeetCode-016 3Sum Closest
- 基于ZooKeeper的分布式锁
- 7-类的加载、连接、初始化
- TCP/IP详解学习笔记(1)-基本概念
- Python实现Pat 1034. Head of a Gang (30)
- python--leetcode598. Range Addition II
- oracle数据库sql语句06 join
- tensorflow系列1:两种方式优化损失函数
- MySQL的CURD