15. 3Sum
来源:互联网 发布:电脑主机 知乎 编辑:程序博客网 时间:2024/06/18 15:06
import java.util.*;public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); Set<ThreeSum> threeSumSet = new TreeSet<ThreeSum>(); for(int i = 0; i < nums.length; ++i) { for(int j = i + 1; j < nums.length; ++j) { int sum = nums[i] + nums[j]; sum = -sum; boolean is_have = find_sum(j+1, nums.length-1, nums, sum); if(!is_have) continue; int k[] = new int[] {nums[i], nums[j], sum}; Arrays.sort(k); ThreeSum threeSum = new ThreeSum(k[0], k[1], k[2]); threeSumSet.add(threeSum); } } ThreeSum tmp = null; for(Iterator<ThreeSum> iterator = threeSumSet.iterator(); iterator.hasNext(); ) { ThreeSum threeSum = iterator.next(); if(tmp == null) res.add(Arrays.asList(new Integer[]{threeSum.a, threeSum.b, threeSum.c})); else if(threeSum.a == tmp.a && threeSum.b == tmp.b && threeSum.c == tmp.c) continue; else { tmp = threeSum; res.add(Arrays.asList(new Integer[]{threeSum.a, threeSum.b, threeSum.c})); } } return res; } public boolean find_sum(int low, int high, int[] nums, int target) { while (low <= high) { int mid = (low + high) / 2; if(nums[mid] == target) return true; else if(nums[mid] > target) high = mid-1; else if(nums[mid] < target) low = mid+1; } return false; } private class ThreeSum implements Comparable<ThreeSum>{ int a, b, c; public ThreeSum(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(ThreeSum o) { if(a < o.a) return -1; else if(a == o.a) { if(b < o.b) return -1; else if(b == o.b) { if(c<o.c) return -1; else if( c == o.c) return 0; else return 1; } else return 1; } else return 1; } }// public static void main(String[] args) {// Solution solution = new Solution();// List<List<Integer>> res = solution.threeSum(new int[] {-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6});// for(int i = 0; i < res.size(); ++i) {// for(int j = 0; j < res.get(i).size(); ++j) {// System.out.print(res.get(i).get(j) + " ");// }// System.out.println();// }// }}
阅读全文
0 0
- 15. 3Sum && 16 sum closet && 18 4sum
- 15. 3Sum 和 18. 4Sum
- 1. Two Sum&15. 3Sum
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- 15. 3Sum
- [leetcode] 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- leetcode 15. 3Sum
- React.js笔记
- hibernate学习笔记03----一级缓存
- java 方法的重载和覆盖
- 链表的选择排序
- codevs 1183 泥泞的道路 (spfa +二分)
- 15. 3Sum
- linux下进程的创建和等待
- (LeetCode) 421. Maximum XOR of Two Numbers in an Array
- 多线程-线程概述等
- Notepad++配置Python开发环境
- hdu 1532 最大流模板
- spring,mybatis事务管理配置与@Transactional注解使用
- Spring04
- ARM最强CPU/GPU来了!A75、G72首发:性能爆炸