GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/3SumWithMultiplicity.java at master · mengli/leetcode

Expand file tree

/

3SumWithMultiplicity.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
47 lines (46 loc) · 1.75 KB
/

3SumWithMultiplicity.java

Copy path

File metadata and controls

47 lines (46 loc) · 1.75 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Given an integer array A, and an integer target, return the number of tuples i, j, k such that i < j < k and A[i] + A[j] + A[k] == target.
*
* As the answer can be very large, return it modulo 10^9 + 7.
*/
class Solution {
public int threeSumMulti(int[] A, int target) {
Map<Integer, Integer> count = new HashMap<>();
for (int a : A) {
if (count.containsKey(a)) {
count.put(a, count.get(a) + 1);
} else {
count.put(a, 1);
}
}
Object[] elements = count.keySet().toArray();
Integer[] integers = Arrays.copyOf(elements, elements.length, Integer[].class);
long ret = 0;
Arrays.sort(integers);
for (int i = 0; i < integers.length; i++) {
for (int j = i; j < integers.length; j++) {
int rest = target - integers[i] - integers[j];
if (count.containsKey(rest) && rest >= integers[j]) {
if (integers[i] == integers[j] && integers[j] == rest) {
ret += calculate(count.get(rest), 3);
} else if (integers[i] == rest && integers[i] != integers[j]) {
ret += (calculate(count.get(integers[i]), 2) * count.get(integers[j]));
} else if (integers[j] == rest && integers[i] != integers[j]) {
ret += (calculate(count.get(integers[j]), 2) * count.get(integers[i]));
} else if (integers[i] == integers[j] && integers[i] != rest) {
ret += (calculate(count.get(integers[j]), 2) * count.get(rest));
} else {
ret += (count.get(integers[i]) * count.get(integers[j]) * count.get(rest));
}
}
}
}
return (int) (ret % (1e9 + 7));
}
private long calculate(long x, long n) {
if (n == 2) {
return x * (x - 1) / 2;
}
return x * (x - 1) * (x - 2) / 6;
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.