中级农民
- 积分
- 124
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-8-4
- 最后登录
- 1970-1-1
|
这个我好像以前写过,就是用binary search在查找的时候稍微优化一下。
- public class Solution {
- public List<List<Integer>> threeSum(int[] nums) {
- List<List<Integer>> res = new LinkedList<>();
- Arrays.sort(nums);
- if (nums == null || nums.length < 3) return res;
- int curi = Integer.MAX_VALUE;
- for (int i = 0; i < nums.length - 2; i++){
- if (curi == nums[i]) continue;
- curi = nums[i];
- int target = 0 - nums[i];
- int h = i+1, t = nums.length - 1;
- if (nums[i+1] + nums[i+2] > target) break;
- if (nums[nums.length - 2] + nums[nums.length - 1] < target ) continue;
- int curh = Integer.MAX_VALUE;
- int curt = Integer.MIN_VALUE;
- while (h < t){
- if (h == -1 || t == -1) break;
- //System.out.println("i = "+ i + ", curh: "+ curh + ", " + nums[i]+ "+" + nums[h] + "+" + nums[t] + "=" + (nums[h] + nums[t]) + ", target = " + target);
- curh = nums[h];
- curt = nums[t];
- if (nums[h] + nums[t] == target){
- List<Integer> cbn = new LinkedList<>();
- cbn.add(nums[i]);
- cbn.add(nums[h]);
- cbn.add(nums[t]);
- res.add(cbn);
- while (h < t && (nums[h] == curh && curt == nums[t])){
- h++;
- }
- while (h < t && curt == nums[t]){
- t--;
- }
- } else if ( nums[h] + nums[t] > target){
- t = helper2(nums, h+1, t, target - curh);
- } else {
- h = helper1(nums, h, t-1, target - curt);
- }
- }
- }
- return res;
- }
-
- public int helper1(int[] nums, int start, int end, int target){
- int h = start;
- int t = end;
- while (h + 1 < t){
- int mid = h + (t - h)/2;
- if (nums[mid] >= target){
- t = mid;
- }
- else if (nums[mid] < target) h = mid;
- }
- if (nums[h] >= target){
- return h;
- }
- if (nums[t] >= target){
- return t;
- }
- return -1;
- }
- public int helper2(int[] nums, int start, int end, int target){
- int h = start;
- int t = end;
- while (h + 1 < t){
- int mid = h + (t - h)/2;
- if (nums[mid] <= target){
- h = mid;
- }
- else if (nums[mid] > target) t = mid;
- }
- if (nums[t] <= target){
- return t;
- }
- if (nums[h] <= target){
- return h;
- }
- return -1;
- }
- }
复制代码
补充内容 (2016-10-17 08:36):
代码巨丑 = =。。
补充内容 (2016-10-17 08:36):
各位凑合看一下 |
|