3SumCloset
来源:互联网 发布:新代数控车床编程实例 编辑:程序博客网 时间:2024/06/07 22:26
原题:
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]]
即从给定数组中找到三个数字和和给定的target最接近。
思路过程&解题思路:
和3Sum思路一样,用双指针,同时找一个变量存储所有遍历过的三个数和target差的绝对值的最小值,最后用targ加这个变量就好了。第二次提交代码就acceptance了。
时间复杂度o(n^2)
结果代码:
public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int dif = nums[0] + nums[1] + nums[2] - target;//初始化dif,target + dif就是最后返回结果 for (int i = 0;i < nums.length;i++){ int l = i + 1,r = nums.length - 1; while (l < r){ int sum = nums[i] + nums[l] + nums[r]; dif = (Math.abs(dif) < Math.abs(sum - target))? dif : (sum - target); if (sum > target) r--; if (sum < target) l++; if (sum == target) return target; } }return target + dif;}
阅读全文
0 0
- 3SumCloset
- 3SumCloset
- [LeetCode] Two Sum, 3Sum ,3SumCloset , 4Sum
- Leetcode 3sumcloset, 3sum, 4sum问题详解
- 3
- 3
- 3
- 3
- 3
- (3)
- 3
- 3
- 3
- 3
- 3
- 3
- 3
- 3
- Mybatis高级查询(一)
- JavaScript: switch用法及注意事项
- Android 设计模式
- token相关
- Leetcode c语言-Remove Duplicates from Sorted Array
- 3SumCloset
- 做自媒体文章的淘宝客面对这两个节日所要注意的几点!
- Http通讯类
- @RestController注解与@Controller 注解的区别
- 微信小程序开发经验总结(五)
- ubuntu14.04下adb devices找不到设备
- iOS Failed to create IXPlaceholder for app bundle ID***
- BAT Android工程师面试流程解析+还原最真实最完整的一线公司面试题
- springboot开发环境热部署(idea下)