You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/2400-2499/2475.Number of Unequal Triplets in Array/README_EN.md
+22
Original file line number
Diff line number
Diff line change
@@ -49,6 +49,28 @@ Note that (2, 0, 4) is not a valid triplet because 2 > 0.
49
49
50
50
## Solutions
51
51
52
+
**Solution 1: Brute Force Enumeration**
53
+
54
+
We can directly enumerate all triples $(i, j, k)$ and count all the ones that meet the conditions.
55
+
56
+
The time complexity is $O(n^3)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.
57
+
58
+
**Solution 2: Sorting + Enumeration of Middle Elements + Binary Search**
59
+
60
+
We can also sort the array $nums$ first.
61
+
62
+
Then traverse $nums$, enumerate the middle element $nums[j]$, and use binary search to find the nearest index $i$ on the left side of $nums[j]$ such that $nums[i] < nums[j]$; find the nearest index $k$ on the right side of $nums[j]$ such that $nums[k] > nums[j]$. Then the number of triples with $nums[j]$ as the middle element and meeting the conditions is $(i + 1) \times (n - k)$, which is added to the answer.
63
+
64
+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$.
65
+
66
+
**Solution 3: Hash Table**
67
+
68
+
We can also use a hash table $cnt$ to count the number of each element in the array $nums$.
69
+
70
+
Then traverse the hash table $cnt$, enumerate the number of middle elements $b$, and denote the number of elements on the left as $a$. Then the number of elements on the right is $c = n - a - b$. At this time, the number of triples that meet the conditions is $a \times b \times c$, which is added to the answer. Then update $a = a + b$ and continue to enumerate the number of middle elements $b$.
71
+
72
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.
Since the problem provides a binary search tree, we can obtain a sorted array through in-order traversal. Then for each query, we can find the maximum value less than or equal to the query value and the minimum value greater than or equal to the query value through binary search.
54
+
55
+
The time complexity is $O(n + m \times \log n)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the number of nodes in the binary search tree and the number of queries, respectively.
0 commit comments