Leetcode10 threesumclosest
来源:互联网 发布:怎么拷贝oracle数据库 编辑:程序博客网 时间:2024/06/06 08:44
1、题目描述
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).
2、解题思路
首先由target开始按照上一篇博文中的方法求是否存在三个元素的和等于target,不存在的话在继续使用接近目标值的数更新目标值target,代码中利用tar=target+/-m来实现。
3、实现代码
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { auto n=nums.size(); for(int i =0 ; i< n-1; ++i) { for(int j = 0; j < n-i-1; ++j) { if(nums[j] > nums[j+1]) { int tmp = nums[j] ; nums[j] = nums[j+1] ; nums[j+1] = tmp; } } }//bubblesort of nums including resorting of index int tar=target; int m=0; int flag=0; do{ for(tar=target-m;tar<=(target+m);tar+=2*m){ for(int i=0;i<n/2;i++){ int j=i+1,k=n-1; int tar1=tar=nums[i]; while(j<k){ int sum=nums[j]+nums[k]; if(sum<tar1) j++; else if(sum>tar1) k--; else{ return tar; } } } } }while(++m); }};
0 0
- Leetcode10 threesumclosest
- threeSumClosest
- leetcode10
- leetcode10.RegularExpressionMatching
- 【LeetCode 16】 threeSumClosest
- [LeetCode]16.threeSumClosest
- leetcode 16 threeSumClosest
- Leetcode10:Regular Experssion Matching
- leetcode10.Linked List Cycle
- leetcode10:Distinct Subsequences
- Leetcode10: Climbing Stairs
- LeetCode10 Regular Expression Matching
- LeetCode10:Regular Expression Matching
- leetcode10. Regular Expression Matching
- Leetcode10 Regular Expression Matching
- LeetCode10 Regular Expression Matching
- LeetCode10. Regular Expression Matching
- LeetCode10. Regular Expression Matching
- 编码和加密
- 类加载器的原理
- C++中怎样将整型值转换为字符串
- 百度地图API详解之事件机制
- java实现排序(3)-希尔排序
- Leetcode10 threesumclosest
- 并查集算法(union-find)
- BZOJ 4813: [Cqoi2017]小Q的棋盘 (树形dp)
- Hitoj 3213 Minimize the cost【Dp】
- 如何通过不同语言获取时间戳
- 利用Spring随时随地获得Request和Session
- Android——编译体系中的【PRODUCT_COPY_FILES】【ALL_PREBUILT】【BUILD_PREBUILT】
- Unity内置的摄像机和屏幕参数
- PTA教辅——特殊a串数列求和