【數組】B065_LC_統計作戰單位數(暴力 / 思維題 / dp)

一、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

方法一:優化

O(n3)O(n^3) 的做法不難,看能不能優化一下:

  • 假如我們確定某個中數 rat[j],那在 j 左邊比 rat[j] 小和 j 右邊比 rat[j] 大的數可組成一對。
  • 同理,在 j 左邊比 rat[j] 大和 j 右邊比 rat[j] 小的數也可組成一對。
  • 再根據乘法定理,jj 位置可組成的總對數 = leftsmallleft_{small} × rightbigright_{big} + leftbigleft_{big} × rightsmallright_{small}
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;
    }
}

複雜度分析

  • 時間複雜度:O(n2)O(n^2)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章