本文正在參加「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…
您的支持是我最大的動力