LeetCode随笔之Array
来源:互联网 发布:2014上半年经济数据 编辑:程序博客网 时间:2024/06/02 06:53
一. Array
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).
**思路:先排序,然后按照顺序举出所有可能。
代码:**
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); int minDis=INT_MAX; int out=0; for(int i=0;i<nums.size()-2;i++){ int l=i+1,r=nums.size()-1; while(l<r){ int sum=nums[i]; sum+=(nums[l]+nums[r]); if(sum==target){out=target;return target;} if(sum<target){l++;minDis=min(minDis,target-sum);if(minDis==target-sum)out=sum;} if(sum>target){r--;minDis=min(minDis,sum-target);if(minDis==sum-target)out=sum;} } } return out; }};
阅读全文
0 0
- LeetCode随笔之Array
- LeetCode随笔之栈
- LeetCode随笔之backtracking
- leetcode 之Rotate Array
- leetcode之rotate array
- LeetCode之Rotate Array
- leetcode之Rotate Array
- Leetcode之Rotate Array
- LeetCode之Rotate Array
- LeetCode随笔之Dynamic programming
- LeetCode随笔之链表
- LeetCode随笔之排序算法
- LeetCode 之 Merge Sorted Array
- LeetCode之Merge Sorted Array
- LeetCode之Merge Sorted Array
- LeetCode之Merge Sorted Array
- leetcode 之 Merge Sorted Array
- leetcode 之Merge Sorted Array
- 深入理解JVM总结-类文件结构
- window cmd常见命令
- RTMP/FLV学习注意要点
- 四个并发工具类CountDownLatch,CyclicBarrier,Semaphore,Exchanger
- hdu6153-exkmp&&脑洞-A Secret
- LeetCode随笔之Array
- 使用freemarker导出word文档包含多张图片
- keras中文文档笔记13——解释CNN的滤波器
- codevs1298 凸包周长 解题报告
- PopuWindow用法
- WCF绑定netTcpBinding寄宿到控制台应用程序
- 袋鼠过河
- oracle增删改查语法
- 【POJ 1094】Sorting it all out (拓扑排序)