一、Problem
There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
- Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
- A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
Input: rating = [2,5,3,4,1]
Output: 3
Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).
二、Solution
方法一:優化
的做法不難,看能不能優化一下:
- 假如我們確定某個中數
rat[j]
,那在j
左邊比rat[j]
小和j
右邊比rat[j]
大的數可組成一對。 - 同理,在
j
左邊比rat[j]
大和j
右邊比rat[j]
小的數也可組成一對。 - 再根據乘法定理, 位置可組成的總對數 = × + ×
class Solution {
public int numTeams(int[] rat) {
int n = rat.length, cnt = 0;
for (int j = 1; j < n-1; j++) {
int ls = 0, lb = 0, rs = 0, rb = 0;
for (int i = 0; i < j; i++) {
if (rat[i] < rat[j]) ls++;
if (rat[i] > rat[j]) lb++;
}
for (int k = j+1; k < n; k++) {
if (rat[k] < rat[j]) rs++;
if (rat[k] > rat[j]) rb++;
}
cnt += ls * rb + lb * rs;
}
return cnt;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,