【Leetcode】1395. Count Number of Teams

記錄演算法發表於2021-01-04

題目地址:

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

給定一個長 n n n陣列 A A A,題目保證無重複數字,問其有多少個三元組 0 ≤ i < j < k < n 0\le i<j<k<n 0i<j<k<n使得 A [ i ] < A [ j ] < A [ k ] A[i]<A[j]<A[k] 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)

相關文章