Input: nums =[4,4,2,4,3]Output: 3Explanation: The following triplets meet the conditions:-(0,2,4) because 4!=2!=3-(1,2,4) because 4!=2!=3-(2,3,4) because 2!=4!=3Since there are 3 triplets, we return3.Note that(2,0,4)is not a valid triplet because 2>0.
We want to count the number of triplets (i, j, k) with i < j < k and all values distinct. Since n is small, we can count the frequency of each unique value, then for each combination of three different values, multiply their frequencies and sum up.
#include<unordered_map>classSolution {
public:int unequalTriplets(vector<int>& nums) {
unordered_map<int, int> freq;
for (int x : nums) freq[x]++;
vector<int> vals;
for (auto& [k, v] : freq) vals.push_back(v);
int n = vals.size(), ans =0;
for (int i =0; i < n; ++i)
for (int j = i+1; j < n; ++j)
for (int k = j+1; k < n; ++k)
ans += vals[i] * vals[j] * vals[k];
return ans;
}
};
import java.util.*;
classSolution {
publicintunequalTriplets(int[] nums) {
Map<Integer, Integer> freq =new HashMap<>();
for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);
List<Integer> vals =new ArrayList<>(freq.values());
int n = vals.size(), ans = 0;
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
for (int k = j+1; k < n; k++)
ans += vals.get(i) * vals.get(j) * vals.get(k);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
fununequalTriplets(nums: IntArray): Int {
val freq = nums.groupingBy { it }.eachCount().values.toList()
var ans = 0val n = freq.size
for (i in0 until n)
for (j in i+1 until n)
for (k in j+1 until n)
ans += freq[i] * freq[j] * freq[k]
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defunequalTriplets(self, nums: list[int]) -> int:
from collections import Counter
freq = list(Counter(nums).values())
ans =0 n = len(freq)
for i in range(n):
for j in range(i+1, n):
for k in range(j+1, n):
ans += freq[i] * freq[j] * freq[k]
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use std::collections::HashMap;
impl Solution {
pubfnunequal_triplets(nums: Vec<i32>) -> i32 {
letmut freq = HashMap::new();
for&x in&nums { *freq.entry(x).or_insert(0) +=1; }
let vals: Vec<_>= freq.values().cloned().collect();
let n = vals.len();
letmut ans =0;
for i in0..n {
for j in i+1..n {
for k in j+1..n {
ans += vals[i] * vals[j] * vals[k];
}
}
}
ans
}
}