【Leetcode】1395. Count Number of Teams

题目地址:

https://leetcode.com/problems/count-number-of-teams/

给定一个长 n n n数组 A A A,题目保证无重复数字,问其有多少个三元组 0 ≤ i < j < k < n 0\le i0i<j<k<n使得 A [ i ] < A [ j ] < A [ k ] A[i]A[i]<A[j]<A[k]或者 A [ i ] > A [ j ] > A [ k ] A[i]>A[j]>A[k] A[i]>A[j]>A[k]

枚举中间数字,然后累加一下左边比它小的个数乘以右边比它大的个数,再累加左边比它大的个数乘以右边比它小的个数。代码如下:

public class Solution {
     
    public int numTeams(int[] rating) {
     
        int res = 0;
        for (int i = 1; i < rating.length - 1; i++) {
     
            int leftGreater = 0, rightGreater = 0, leftSmaller = 0, rightSmaller = 0;
            for (int j = 0; j < i; j++) {
     
                if (rating[j] > rating[i]) {
     
                    leftGreater++;
                } else {
     
                    leftSmaller++;
                }
            }
            
            for (int j = i + 1; j < rating.length; j++) {
     
                if (rating[j] > rating[i]) {
     
                    rightGreater++;
                } else {
     
                    rightSmaller++;
                }
            }
            
            res += leftSmaller * rightGreater;
            res += leftGreater * rightSmaller;
        }
        
        return res;
    }
}

时间复杂度 O ( n 2 ) O(n^2) O(n2),空间 O ( 1 ) O(1) O(1)

你可能感兴趣的:(#,二分,位运算与数学,leetcode,算法)