当前位置:网站首页>Leetcode 2001. Number of groups of interchangeable rectangles (brute force enumeration failed)

Leetcode 2001. Number of groups of interchangeable rectangles (brute force enumeration failed)

2022-06-10 03:57:00 I'm not xiaohaiwa~~~~

From... With a subscript 0 Start with a two-dimensional integer array rectangles To express n A rectangle , among rectangles[i] = [widthi, heighti] It means the first one i The width and height of a rectangle .

If two rectangles i and j(i < j) Have the same aspect ratio , These two rectangles Interchangeable . A more standardized statement is , Two rectangles satisfy widthi/heighti == widthj/heightj( Use real division instead of integer division ), These two rectangles Interchangeable .

Calculate and return rectangles How many of them are right Interchangeable rectangular .

Example 1:

 Input :rectangles = [[4,8],[3,6],[10,20],[15,30]]
 Output :6
 explain : Press the subscript below ( from  0  Start ) List the pairing of interchangeable rectangles :
-  rectangular  0  And rectangle  14/8 == 3/6
-  rectangular  0  And rectangle  24/8 == 10/20
-  rectangular  0  And rectangle  34/8 == 15/30
-  rectangular  1  And rectangle  23/6 == 10/20
-  rectangular  1  And rectangle  33/6 == 15/30
-  rectangular  2  And rectangle  310/20 == 15/30

Example 2:

 Input :rectangles = [[4,5],[7,8]]
 Output :0
 explain : There are no pairs of interchangeable rectangles .

Tips :

  • n == rectangles.length
  • 1 <= n <= 10^5
  • rectangles[i].length == 2
  • 1 <= widthi, heighti <= 10^5

Code:

class Solution {
    
public:
    long long interchangeableRectangles(vector<vector<int>>& rectangles) {
    
        long long res=0;
    
        int size=rectangles.size();
        for(int i=0;i<size;i++)
        {
    
            for(int j=i+1;j<size;j++)
            {
    
                vector<int>sub1=rectangles[i];
                vector<int>sub2=rectangles[j];
                
                if(sub1[0]*sub2[1]==(sub1[1]*sub2[0]))
                {
    
                    res++;
                }
            }
        }
        return res;
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091350598867.html