Advertisement
Guest User

923. 3Sum With Multiplicity

a guest
Feb 17th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.19 KB | None | 0 0
  1. // https://leetcode.com/problems/3sum-with-multiplicity/discuss/181128/10-lines-Super-Super-Easy-Java-Solution
  2. class Solution {
  3.     public int threeSumMulti2Sum(int[] A, int target) {
  4.         if (A == null || A.length == 0) {
  5.             return 0;
  6.         }
  7.        
  8.         HashMap<Integer, Integer> map = new HashMap<>();
  9.         int res = 0;
  10.         int mod = 1000000007;
  11.        
  12.         for (int i=0; i<A.length; i++) {
  13.             res = (res + map.getOrDefault(target - A[i], 0))%mod;
  14.             for (int j=0; j<i; j++) {
  15.                 map.put(A[i]+A[j], map.getOrDefault(A[i]+A[j],0)+1);
  16.             }
  17.         }
  18.        
  19.         return res;
  20.     }
  21.    
  22.     // https://leetcode.com/problems/3sum-with-multiplicity/discuss/181131/C%2B%2BJavaPython-O(N-%2B-101-*-101)
  23.     public int threeSumMulti(int[] A, int target) {
  24.         if (A == null || A.length < 3) {
  25.             return 0;
  26.         }
  27.        
  28.         HashMap<Integer, Long> map = new HashMap<>();
  29.         long res = 0;
  30.        
  31.         for (int a : A) {
  32.             map.put(a, map.getOrDefault(a,new Long(0))+1);
  33.         }
  34.        
  35.         List<Integer> uniqueNums = new ArrayList<>(map.keySet());
  36.         Collections.sort(uniqueNums);
  37.         int n = uniqueNums.size();
  38.        
  39.         for (int i=0; i<n; i++) {
  40.             for (int j=i; j<n; j++) {
  41.                 int n1 = uniqueNums.get(i);
  42.                 int n2 = uniqueNums.get(j);
  43.                 int n3 = target - (n1+n2);
  44.                
  45.                 if (!map.containsKey(n3)) {
  46.                     continue;
  47.                 }
  48.                
  49.                 long c1 = map.get(n1);
  50.                 long c2 = map.get(n2);
  51.                 long c3 = map.get(n3);
  52.                 long add = 0;
  53.                
  54.                 if (n1 == n2) {
  55.                     if (n2 == n3) {
  56.                         add = c1*(c1-1)*(c1-2)/6;
  57.                     } else {
  58.                         add = (c1*(c1-1)/2) * c3;
  59.                     }
  60.                 } else if (n2 < n3) {
  61.                     add = c1*c2*c3;
  62.                 }
  63.                
  64.                 res += add;
  65.             }
  66.         }
  67.        
  68.         return (int)(res % (1e9 + 7));
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement