【LeetCode】3Sum,3Sum Closest 题解报告
来源:互联网 发布:地形图矢量化软件 编辑:程序博客网 时间:2024/05/17 02:52
【题目1】3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
【解析】
根据题目的意思,需要在一个数组中找到所有的三元组,使这3个数的和为0.跟Two Sum这道题很像。只不过这道题是找出所有可行的结果,并且结果集中不能存在重复。
这道题依然有两种思路,最直接的想法是进行3重循环,遍历所有的可能,这样的时间效率是O(n^3).显然,时间效率过高。
思路2:先对数组进行排序(递增),效率是O(nlogn),然后先确定第一个值,再在有序的序列中查找两个满足要求的数。由于是有序的,所以查找效率是O(n),因此,总体的时间效率是O(n^2).
public static List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); Set<List<Integer>> res = new HashSet<List<Integer>>(); for(int i=0;i<nums.length;i++){ int target = 0 - nums[i]; int j = i+1, k=nums.length-1; while(j<k){ if(nums[k] + nums[j] == target){ List<Integer> tmp = new ArrayList<Integer>(); tmp.add(nums[i]); tmp.add(nums[j]); tmp.add(nums[k]); res.add(tmp); j++; k--; } else if(nums[k] + nums[j] < target) j++; else k--; } } return new ArrayList<List<Integer>>(res);}
【题目2】3Sum Closest
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).
【解析】
这道题跟上面的类似,解题思路是一样的。先对数组进行排序,然后确定第一个数,再在有序的数组中遍历找到最接近目标值的数。
public static int threeSumClosest(int[] nums, int target) { if(nums == null || nums.length < 3) return 0; Arrays.sort(nums); int res = 0; int diff = Integer.MAX_VALUE; int len = nums.length; for(int i=0;i<len-2;i++){ int j = i+1, k=len-1; while(j<k){ int sum = nums[i] + nums[j] + nums[k]; if(Math.abs(sum - target) < diff){ diff = Math.abs(sum - target); res = sum; } if(sum < target){ j++; }else if(sum > target){ k--; }else{ return sum; } } } return res; }
- 【LeetCode】3Sum,3Sum Closest 题解报告
- LeetCode题解:3sum closest
- LeetCode题解:3Sum Closest
- [LeetCode]3Sum Closest题解
- Leetcode题解-3Sum&3Sum Closest
- 3Sum Closest题解
- 题解:3Sum Closest
- leetcode 题解 || 3Sum Closest 问题
- LeetCode 题解(76): 3Sum Closest
- LeetCode题解——3Sum Closest
- LeetCode题解-16-3Sum Closest
- 16. 3Sum Closest LeetCode题解
- leetcode题解-16. 3Sum Closest
- 【LeetCode】3Sum Closest 解题报告
- LeetCode 解题报告 3Sum Closest
- LeetCode解题报告--3Sum Closest
- [leetcode] 16. 3Sum Closest 解题报告
- leetcode(16) 3Sum Closest解题报告
- linux 命令2
- [我所知道的BIOS]->[Remaining POST Tasks] 11
- 运算符优先级
- Linux 内核 Starting kernel ... 串口无输出问题归纳总结
- tolua学习资料汇总贴
- 【LeetCode】3Sum,3Sum Closest 题解报告
- mysql merge
- Quartz配合Spring使用的一种方法
- NOIP 2005 等价表达式
- LeetCode No145 Binary Tree Postorder Traversal
- JAVA 异常
- Angular2中使用bootstrap
- POJ 2418Hardwood Species(搜索二叉树)
- BST iterator