LeetCode 5369. Statistics combat unit number (brute force)

1. Topic

n soldiers stand in a row. Each soldier has a unique score rating.

Every three soldiers to form a combat unit, grouping rules are as follows:

  • Selected index from the team were three soldiers i, j, k, and their scores were rating[i]、rating[j]、rating[k]
  • Combat units must meet: rating[i] < rating[j] < rating[k] 或者 rating[i] > rating[j] > rating[k]where0 <= i < j < k < n

Please return the above conditions can be set up according to the number of combat units. Each soldier can be part of multiple combat units.

示例 1:
输入:rating = [2,5,3,4,1]
输出:3
解释:我们可以组建三个作战单位 (2,3,4)(5,4,1)(5,3,1) 。

示例 2:
输入:rating = [2,1,3]
输出:0
解释:根据题目条件,我们无法组建作战单位。

示例 3:
输入:rating = [1,2,3,4]
输出:4
 
提示:
n == rating.length
1 <= n <= 200
1 <= rating[i] <= 10^5

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/count-number-of-teams
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

2.1 brute force solution

  • A small amount of data, three-layer direct circulation
class Solution {
public:
    int numTeams(vector<int>& rating) {
    	int i, j, k, sum = 0, n = rating.size();
    	for(i = 0; i < n-2; ++i)
    		for(j = i+1; j < n-1; ++j)
    			for(k = j+1; k < n; ++k)
    				if((rating[i] < rating[j] && rating[j] < rating[k])
    					 ||(rating[i] > rating[j] && rating[j] > rating[k]))
    					sum++;
    	return sum;
    }
};

140 ms 7.6 MB

2.2 brute force optimization

  • Found about each position of the number of large and small than
  • sum += lsmall*rLarge + lLarge*rsmall
class Solution {
public:
    int numTeams(vector<int>& rating) {
    	int i, j, lsmall, lLarge, rsmall, rLarge, sum = 0, n = rating.size();
    	for(i = 1; i < n-1; ++i)
    	{
    		lsmall = lLarge = rsmall = rLarge = 0;
    		for(j = 0; j < i; ++j)
    		{
    			if(rating[j] < rating[i])
    				lsmall++;
    			if(rating[j] > rating[i])
    				lLarge++;
    		}
    		for(j = i+1; j < n; ++j)
    		{
    			if(rating[j] < rating[i])
    				rsmall++;
    			if(rating[j] > rating[i])
    				rLarge++;
    		}
    		sum += lsmall*rLarge + lLarge*rsmall;
    	}
    	return sum;
    }
};

8 ms 7.3 MB

Published 787 original articles · won praise 1151 · Views 310,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105176543