Advertisement
uopspop

Untitled

Jul 10th, 2021
1,303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. class Solution {
  2.     public List<List<Integer>> threeSum(int[] nums) {
  3.        
  4.         Arrays.sort(nums);
  5.        
  6.         Set<List<Integer>> results = new HashSet<>(); // use Set to remove duplicate element
  7.        
  8.         Map<Integer, Integer> val_index = new HashMap<>();
  9.        
  10.         // fix the first number
  11.         for (int i = 0; i < nums.length ;i++) {
  12.             int num = nums[i];
  13.             int num_target = 0 - (num);
  14.            
  15.             for (int j = i; j < nums.length ;j++) {
  16.                 if (j == i) continue;
  17.                
  18.                 int num_second = nums[j];
  19.                 int num_third_target = num_target - num_second;
  20.                
  21.                 // check if exist
  22.                 Integer i_num_third = val_index.get(num_third_target);
  23.                 if (i_num_third != null) {
  24.                     if (i_num_third == i || i_num_third == j) continue;
  25.                    
  26.                     // collect it
  27.                     add(nums, results, i, j, i_num_third); // TODO
  28.                    
  29.                 }
  30.                
  31.                 val_index.put(num_second, j);
  32.                                
  33.             }
  34.            
  35.         } // end of if
  36.        
  37.         List<List<Integer>> results_list = new ArrayList<>(results);
  38.         return results_list;
  39.        
  40.     }
  41.    
  42.     public void add(int[] nums, Set<List<Integer>> results, int i, int j, int k) {
  43.        
  44.         Integer[] array = new Integer[3];
  45.         array[0] = nums[i];
  46.         array[1] = nums[j];
  47.         array[2] = nums[k];
  48.        
  49.         Arrays.sort(array); // make sure no duplicate witth varying orders are added
  50.        
  51.         results.add(Arrays.asList(array));
  52.     }
  53.    
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement