0016_3Sum Closest
来源:互联网 发布:终结者4知乎 编辑:程序博客网 时间:2024/06/03 18:47
JAVA
在看过0015_3Sum的解题思路之后,本题作为练习,采用同样的思路进行运算。即使在看过3Sum之后,写代码时仍然有多处边界判断不准确,导致溢出或死循环。。。不过这种方法的效率还可以,大概排在前1/3左右。
public class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int result = nums[0] + nums[1] + nums[2]; int temp; for(int i = 0; i < nums.length - 2;){ for(int j = i+1, k = nums.length - 1; j < k;){ temp = nums[i] + nums[j] + nums[k]; if(Math.abs(temp - target) <= Math.abs(result - target)){ result = temp; if(Math.abs(temp - target) == 0){ return result; } } if(temp < target){ ++j; while(j < k && nums[j] == nums[j-1]){ ++j; } } if(temp > target){ --k; while(j < k && nums[k] == nums[k+1]){ --k; } } } ++i; while(i < nums.length && nums[i] == nums[i-1]){ ++i; } } return result; }}
阅读全文
0 0
- 0016_3Sum Closest
- 【LeetCode】16_3Sum Closest
- LeetCode 16_3Sum Closest
- leetcode第一刷_3Sum Closest
- LeetCode之16_3Sum Closest
- leetcode第一刷_3Sum
- 【LeetCode】15_3Sum
- LeetCode 15_3Sum
- LeetCode之15_3Sum
- closest
- Closest
- leetcode15&16_3Sum&4Sum
- closest 用法
- Leetcode_3sum-closest
- closest jquery
- LeetCode_3Sum Closest
- Leetcode_3Sum Closest
- 2Sum closest vs. 2Minus closest
- java NIO与IO的区别
- Spring3.1.0实现原理分析(十二).MVC核心类DispatcherServlet初始化过程
- df -h命令卡住,报错 kernel: nfs: server xx.xx.xx.xx not responding, still trying
- 开始用react-native工作
- 数组与集合的应用之数组演练(获取一维数组最小值)
- 0016_3Sum Closest
- py-faster-rcnn详解(3)——train.py接口说明
- MySQL优化系列(五)--数据库存储引擎(主要分析对比InnoDB和MyISAM以及讲述Mrg_Myisam分表)
- C4.5算法
- 阿里云服务器从购买,备案,安装部署中遇到的一些坑
- IPC之—消息队列
- 中文分词器性能比较
- POJ 1944 Fiber Communications 笔记
- 数组与集合的应用之数组演练(将二维数组中的行列互换)