Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. class Solution {
  2.     List<Integer> sort(int a, int b, int c) {
  3.         if (a > b) {
  4.             int temp = a;
  5.             a = b;
  6.             b = temp;
  7.         }
  8.         if (a > c) {
  9.             int temp = a;
  10.             a = c;
  11.             c = temp;
  12.         }
  13.         if (b > c) {
  14.             int temp = b;
  15.             b = c;
  16.             c = temp;
  17.         }
  18.         return Arrays.asList(a, b, c);
  19.     }
  20.  
  21.     boolean isUniqueIndex(Set<Integer> indices, int index1, int index2) {
  22.         if (indices.contains(index1) && indices.contains(index2)) {
  23.             return indices.size() > 2;
  24.         }
  25.         if (indices.contains(index1) || indices.contains(index2)) {
  26.             return indices.size() > 1;
  27.         }
  28.         return indices.size() > 0;
  29.     }
  30.  
  31.     public List<List<Integer>> threeSum(int[] nums) {
  32.         Set<List<Integer>> solutions = new HashSet<>();
  33.         Map<Integer, Set<Integer>> numToIndices = new HashMap<>();
  34.  
  35.         // Fill out the map
  36.         for (int i=0; i<nums.length; ++i) {
  37.             int num = nums[i];
  38.             if (!numToIndices.containsKey(num)) {
  39.                 numToIndices.put(num, new HashSet<>());
  40.             }
  41.             numToIndices.get(num).add(i);
  42.         }
  43.  
  44.         // Check for tiples
  45.         for (int i=0; i<nums.length; ++i) {
  46.             for (int j=i+1; j<nums.length; ++j) {
  47.                 int first = nums[i];
  48.                 int second = nums[j];
  49.                 int third = -(first + second);
  50.                 // Potential solution
  51.                 if (numToIndices.containsKey(third)) {
  52.                     if (isUniqueIndex(numToIndices.get(third), i, j)) {
  53.                         // Tuple is unique indices
  54.                         solutions.add(sort(first, second, third));
  55.                     }
  56.                 }
  57.             }
  58.         }
  59.  
  60.         List<List<Integer>> toReturn = new ArrayList<>();
  61.         toReturn.addAll(solutions);
  62.         return toReturn;
  63.    }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement