# LEETCODE 1395. Count Number of Teams 解题思路分析

`n` 名士兵站成一排。每个士兵都有一个 独一无二 的评分 `rating` 。

• 从队伍中选出下标分别为 i、j、k 的 3 名士兵，他们的评分分别为 rating[i]、rating[j]、rating[k]
• 作战单位需满足： rating[i] < rating[j] < rating[k] 或者 rating[i] > rating[j] > rating[k] ，其中  0 <= i < j < k < n

```输入：rating = [2,5,3,4,1]

```输入：rating = [2,1,3]

```输入：rating = [1,2,3,4]

• `n == rating.length`
• `1 <= n <= 200`
• `1 <= rating[i] <= 10^5`

```public int numTeams(int[] rating) {
int res=0;
for(int i=0;i<rating.length;i++){
for(int j=i+1;j<rating.length;j++){
for(int k=j+1;k<rating.length;k++){
if(rating[j]>rating[i]&&rating[k]>rating[j]) res++;
if(rating[j]<rating[i]&&rating[k]<rating[j]) res++;
}
}
}
return res;
}```

Runtime: 16 ms, faster than 66.17% of Java online submissions for Count Number of Teams.

Memory Usage: 37.1 MB, less than 100.00% of Java online submissions for Count Number of Teams.

```public int numTeams(int[] rating) {
int res=0;
for(int i=1;i<rating.length-1;i++){
int leftbigger=0;
int leftSmaller=0;
for(int j=0;j<i;j++){
if(rating[j]>rating[i])leftbigger++;
if(rating[j]<rating[i])leftSmaller++;
}
int rightbigger=0;
int rightSmaller=0;
for(int j=i+1;j<rating.length;j++){
if(rating[j]>rating[i])rightbigger++;
if(rating[j]<rating[i])rightSmaller++;
}
res+= leftbigger*rightSmaller+leftSmaller*rightbigger;
}
return res;
}```

Runtime: 2 ms, faster than 99.71% of Java online submissions for Count Number of Teams.

Memory Usage: 37.1 MB, less than 100.00% of Java online submissions for Count Number of Teams.

Kotlin版本：

```fun numTeams(rating: IntArray): Int {
var res :Int = 0;
for(i in 1..(rating.lastIndex-1)){
var leftBigger=0;
var leftSmaller=0;
for(j in 0..i-1){
if(rating[j]<rating[i]) leftSmaller++;
else if(rating[j]>rating[i]) leftBigger++;
}
var rightBigger=0;
var rightSmaller=0;
for(j in i+1..rating.lastIndex){
if(rating[j]<rating[i]) rightSmaller++;
else if(rating[j]>rating[i]) rightBigger++;
}
res+=leftBigger*rightSmaller+leftSmaller*rightBigger;
}
return res;
}```

Runtime: 176 ms, faster than 90.91% of Kotlin online submissions for Count Number of Teams.

Memory Usage: 34.7 MB, less than 100.00% of Kotlin online submissions for Count Number of Teams.