LeetCode 3Sum Closest
来源:互联网 发布:怎么登陆淘宝卖家中心 编辑:程序博客网 时间:2024/05/02 01:08
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).题意:给出一个数组及一个目标数,求数组中三个数加起来与目标数最接近的数
思路:与LeetCode 4Sum(backtrace+剪枝)有些相似
代码如下:
class Solution { private int kSum(int[] nums, int start, int k,int cur_sum, int target) { int len = nums.length; if (start >= len || 0 == k) return 0; if (2 == k) { int end = len - 1; int ans = Integer.MAX_VALUE; while (start < end) { int sum = nums[start] + nums[end]; if (sum + cur_sum == target) { while (start < end && nums[start] == nums[start + 1]) start++; start++; while (start < end && nums[end] == nums[end - 1]) --end; --end; ans = target; return ans; } else if (sum + cur_sum < target) { while (start < end && nums[start] == nums[start + 1]) start++; start++; if (Integer.MAX_VALUE == ans) { ans = cur_sum + sum; } else if (Math.abs(cur_sum + sum - target) < Math.abs(ans - target)) { ans = cur_sum + sum; } } else { while (start < end && nums[end] == nums[end - 1]) end--; end--; if (Integer.MAX_VALUE == ans) { ans = cur_sum + sum; } else if (Math.abs(cur_sum + sum - target) < Math.abs(ans - target)) { ans = cur_sum + sum; } } } return ans; } int ans = Integer.MAX_VALUE; for (int i = start; i <= (len - k); i++) { if (i > start && nums[i] == nums[i - 1]) continue; int tmp = kSum(nums, i + 1, k - 1, cur_sum + nums[i], target); if (Integer.MAX_VALUE == ans) { ans = tmp; } else if (Math.abs(tmp - target) < Math.abs(ans - target)) { ans = tmp; } } return ans; } public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int ans = kSum(nums, 0, 3, 0, target); return ans; }}
0 0
- 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
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- CHtmlView 处理/禁止 JavaScript 脚本错误!
- 高级并发学习之Samphere同步工具学习
- 怎么使用 JavaScript 将网站后台的数据变化实时更新到前端?
- javascript中的window.location.search方法简介
- 利用HttpURLConnection发送post请求上传多个文件
- LeetCode 3Sum Closest
- UI线程阻塞监控工具----BlockCanary
- 虚拟机
- Xen概述
- ExtJs中的事件机制
- 安卓初学二之控件初步(一)
- 游戏任务系统设计思路
- Redis入门基础
- OpenGL 实用程序框架设计实现-Windows上的小框架: