The title
The n rectangles are represented by a two-dimensional array of integers with subscripts starting at 0, with rectangles[I] = [widthi, heighti] representing the width and height of the ith rectangle.
Two rectangles I and j are considered interchangeable if they have the same aspect ratio (I < j). More formally, two rectangles are considered interchangeable if they satisfy widthi/ Heighti == widthj/heightj (using real rather than integer division).
Calculates and returns how many pairs of rectangles are interchangeable.
Example 1: input: rectangles = [[4,8],[3,6],[10,20],[15,30]] output: 6 explanation: the pairs of interchangeable rectangles are listed below by subscript (starting from 0) : - rectangles 0 and rectangles 1: 4/8 == 3/6 - Rectangles 0 and 2:4/8 == 10/20 - Rectangles 0 and 3:4/8 == 15/30 - Rectangles 1 and 2:3/6 == 10/20 - Rectangles 1 and 3:3/6 == 10/20 - Rectangles 1 and 3: 3/6 == 15/30 - rectangles 2 and 3:10/20 == 15/30 example 2: input: rectangles = [[4,5],[7,8]] output: 0 explanation: there are no pairs of interchangeable rectangles.Copy the code
Tip:
n == rectangles.length 1 <= n <= 105 rectangles[i].length == 2 1 <= widthi, heighti <= 105
Their thinking
class Solution: def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: from collections import defaultdict resDict = defaultdict(list) from fractions import Fraction for arr in rectangles: x,y = arr[0],arr[1] fa = Fraction(x,y) resDict[(fa.numerator,fa.denominator)].append(arr) res = 0 for key,val in resDict.items(): length = len(val) if length >=2: res+= (length*(length-1))//2 return res if __name__ == '__main__': Rectangles = [[4, 8], [3], [10, 20], [15, 30]] result = Solution () interchangeableRectangles (rectangles) print (result)Copy the code