diff --git a/solution/0900-0999/0923.3Sum With Multiplicity/README.md b/solution/0900-0999/0923.3Sum With Multiplicity/README.md index 208d492a56d04..7a9a9b5d36e21 100644 --- a/solution/0900-0999/0923.3Sum With Multiplicity/README.md +++ b/solution/0900-0999/0923.3Sum With Multiplicity/README.md @@ -68,10 +68,29 @@ arr[i] = 1, arr[j] = arr[k] = 2 出现 12 次: ``` -### **...** - -``` - +### **C++** + +```cpp +class Solution { +public: + int threeSumMulti(vector& arr, int target) { + unordered_map c; + for (int a : arr) c[a]++; + long res = 0; + for (auto it : c) + for (auto it2 : c) { + int i = it.first, j = it2.first, k = target - i - j; + if (!c.count(k)) continue; + if (i == j && j == k) + res += c[i] * (c[i] - 1) * (c[i] - 2) / 6; + else if (i == j && j != k) + res += c[i] * (c[i] - 1) / 2 * c[k]; + else if (i < j && j < k) + res += c[i] * c[j] * c[k]; + } + return res % int(1e9 + 7); + } +}; ``` diff --git a/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md b/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md index 75fbb07f25b10..312313f07c5a0 100644 --- a/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md +++ b/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md @@ -58,10 +58,29 @@ and two 2s from [2,2,2,2] in 6 ways. ``` -### **...** - -``` - +### **C++** + +```cpp +class Solution { +public: + int threeSumMulti(vector& arr, int target) { + unordered_map c; + for (int a : arr) c[a]++; + long res = 0; + for (auto it : c) + for (auto it2 : c) { + int i = it.first, j = it2.first, k = target - i - j; + if (!c.count(k)) continue; + if (i == j && j == k) + res += c[i] * (c[i] - 1) * (c[i] - 2) / 6; + else if (i == j && j != k) + res += c[i] * (c[i] - 1) / 2 * c[k]; + else if (i < j && j < k) + res += c[i] * c[j] * c[k]; + } + return res % int(1e9 + 7); + } +}; ``` diff --git a/solution/0900-0999/0923.3Sum With Multiplicity/Solution.cpp b/solution/0900-0999/0923.3Sum With Multiplicity/Solution.cpp new file mode 100644 index 0000000000000..82d9fbc52a748 --- /dev/null +++ b/solution/0900-0999/0923.3Sum With Multiplicity/Solution.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int threeSumMulti(vector& arr, int target) { + unordered_map c; + for (int a : arr) c[a]++; + long res = 0; + for (auto it : c) + for (auto it2 : c) { + int i = it.first, j = it2.first, k = target - i - j; + if (!c.count(k)) continue; + if (i == j && j == k) + res += c[i] * (c[i] - 1) * (c[i] - 2) / 6; + else if (i == j && j != k) + res += c[i] * (c[i] - 1) / 2 * c[k]; + else if (i < j && j < k) + res += c[i] * c[j] * c[k]; + } + return res % int(1e9 + 7); + } +};