1725. Number Of Rectangles That Can Form The Largest Square(python)|Python 主题月

本文正在参加「Python主题月」,详情查看 活动连接markdown

描述

You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.网络

You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.less

Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.ide

Return the number of rectangles that can make a square with a side length of maxLen.函数

Example 1:oop

Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]
Output: 3
Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
复制代码

Example 2:post

Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]
Output: 3
复制代码

Note:spa

1 <= rectangles.length <= 1000
rectangles[i].length == 2
1 <= li, wi <= 109
li != wi
复制代码

解析

根据题意,就是给出了矩形列表,将每一个矩形切割能够造成正方形,问能够造成的边长最大的正方形的个数。正方形的边长就是靠矩形的较小边,因此找出全部矩形的最小边,而后统计个数字典,找出最大边的出现个数便可。这里用到了 Python 的内置函数 collections.Counter() ,有点取巧。code

解答

class Solution(object):
    def countGoodRectangles(self, rectangles):
        """
        :type rectangles: List[List[int]]
        :rtype: int
        """
        c = collections.Counter([min(r) for r in rectangles])
        k = c.keys()
        return c[max(k)]
        	      
		
复制代码

运行结果

Runtime: 160 ms, faster than 18.45% of Python online submissions for Number Of Rectangles That Can Form The Largest Square.
Memory Usage: 14 MB, less than 58.67% of Python online submissions for Number Of Rectangles That Can Form The Largest Square.
复制代码

解析

上面的直接用到了内置函数,若是不用内置函数,直接使用字典 d 保存每一个矩形中的较小的边的个数,最后找到最大的边的个数便可。这里结果比较使人满意,居然双双接近 100%,其实 leetcode 这个测评我以为和网络环境有关系,有时候特别快,有时候很通常。orm

解答

class Solution(object):
    def countGoodRectangles(self, rectangles):
        """
        :type rectangles: List[List[int]]
        :rtype: int
        """
        d = {}
        for r in rectangles:
            p = min(r)  
            if p in d:
                d[p] += 1 
            else:
                d[p] = 1 
        return d[max(d.keys())]  
复制代码

运行结果

Runtime: 140 ms, faster than 97.60% of Python online submissions for Number Of Rectangles That Can Form The Largest Square.
Memory Usage: 13.9 MB, less than 99.04% of Python online submissions for Number Of Rectangles That Can Form The Largest Square.
复制代码

原题连接:leetcode.com/problems/nu…

您的支持是我最大的动力

相关文章
相关标签/搜索