【Leetcode】之3Sum Closest
来源:互联网 发布:java自我介绍一分钟 编辑:程序博客网 时间:2024/05/17 01:10
一.问题描述
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).
二.我的解题思路
这道题和上一道题几乎完全一样,这道题还更简单一些,因为只需要返回sum值而不需要返回具体的三个数。沿用上一题的排序+双指针的思路,测试通过的程序如下:
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); int len=nums.size(); int tmp_min=100000; int res; for(int i=0;i<len;i++) { if(i>0&&nums[i]==nums[i-1]) continue; int st=i+1;int end=len-1; while(st<end) { int curr_value=nums[i]+nums[st]+nums[end]; int curr_dist=abs(curr_value-target); if(curr_dist<tmp_min) { tmp_min=curr_dist; res=curr_value; } if(curr_value>target) end--; if(curr_value<target) st++; if(curr_value==target) return target; } } return res; }};
0 0
- leetcode之3Sum Closest
- LeetCode之3Sum Closest
- 【Leetcode】之3Sum Closest
- leetcode之3Sum Closest
- leetcode之 3Sum Closest
- LeetCode进阶之路(3Sum Closest)
- leetcode之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
- 面试时如何谈自己的兴趣爱好
- 农村深化改革方案公布 宅基地制度改革思路确定
- 【应用组件:EventBus】实例演示
- Oracle GoldenGate的思想天空--感悟OGG的本质
- php生成多条sql记录
- 【Leetcode】之3Sum Closest
- 欢迎使用CSDN-markdown编辑器
- Java SE复习笔记62
- MATLAB函数汇总
- android:关于serializable
- 继承与派生
- Solr学习 DIH增量、定时导入并检索数据
- spring和springmvc的配置文件写法
- android java 在同时支持ipv4 与 ipv6 状况下,仅支持ipv4 或 ipv6的方法(测试中)