LeetCode 16. 3Sum Closest
来源:互联网 发布:摄像头阅卷软件 编辑:程序博客网 时间:2024/06/14 03:38
- 题目
- 题意
- 分析
- 代码
题目
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).
题意
给出一个数组和一个target,在这个数组中找出和最接近target的三个数。比如:
给出数组 S = {-1 2 1 -4}, target = 1.最接近target的和为 2. (-1 + 2 + 1 = 2).
分析
这道题可以用深度搜索,考虑到深度只为3,我做了简化。
首先选定第一个数one,那么剩下的两个数two、three符合条件,one+two+three ~ target。
考虑到two和three是数组中不同下标的值,可以分别从给出数组头和尾部往中间找。这样一来,时间复杂度从 O(n^3) 降为 O(n*n)。
思路
1、首先先对数组进行排序处理。
2、对 result 进行初始化赋值
3、for 循环选择,得到第一个数字one。
4、从数字两端向中间靠拢找的two、three。
5、curr 等于当前的 one+two+three。
- A. 如果curr更接近target,result = curr。
- B. 如果curr 小于 target,two向后移一位。
- C.如果curr 大于 target,three向前移一位。
- D.如果curr 等于 target,那么正好,找到了最接近target的值,可以直接返回了。
代码
int threeSumClosest(vector<int>& nums,int target) { int result = 0; std::sort(nums.begin(), nums.end()); for(int i=0;i<nums.size()&&i<3;i++) result+=nums[i]; for(int one=0;one<nums.size()-2;one++){ int two=one+1, three =nums.size()-1; while(two<three){ int curr = nums[one]+nums[two]+nums[three]; if(abs(curr-target)<abs(result-target)) result = curr; if(curr>target) three--; else if(curr<target) two++; else if(curr==target) return target; } } return result;}
125 / 125 test cases passed.
Runtime: 12 ms
0 0
- LeetCode 16. 3Sum Closest
- LeetCode --- 16. 3Sum Closest
- [Leetcode] 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- [leetcode] 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- LeetCode - 16. 3Sum Closest
- [LeetCode]16. 3Sum Closest
- LeetCode 16. 3Sum Closest
- LeetCode *** 16. 3Sum Closest
- Leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【LeetCode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 决策树
- 安卓中绘制2D、3D图形
- PHP $_SERVER详解
- 4-way handshake
- jzoj P1666 【AHOI2009】飞行棋
- LeetCode 16. 3Sum Closest
- 实战java高并发程序设计第一章读书笔记
- Android:怎样隐藏EditText控件的下划线
- 聊聊游戏辅助那些事上部第一篇——过掉那些讨厌的游戏保护。
- 基于单Redis节点的分布式锁
- 【算法】 多特征融合粒子滤波
- Palindrome Partitioning I,II
- 锁优化的思路和方法
- angular2系列教程(七)Injectable、Promise、Interface、使用服务