【LeetCode刷题】867 转置矩阵 || 836 矩形重叠

867、转置矩阵

题目描述:
给定一个矩阵 A, 返回 A 的转置矩阵。矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

示例 1:
输入:[[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]

示例 2:
输入:[[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]

solution:把原来的每列元素转变成每行

#方法一
class Solution:
    def transpose(self, A):
        a=[]
        for j in range(len(A[0])): #每列
            t=[]
            for i in range(len(A)):#每行
                t.append(A[i][j])
            a.append(t)
        return a
A = [[1,2,3],[4,5,6]]
solution = Solution()
print solution.transpose(A)

836、矩形重叠

题目描述:
矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。给出两个矩形,判断它们是否重叠并返回结果。

示例 1:
输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]
输出:true

示例 2:
输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]
输出:false

class Solution(object):
    def rectangle(self,rec1,rec2):
        # x1 = rec1[0]
        # y1 = rec1[1] #left-bottom
        # x2 = rec1[2]
        # y2 = rec1[3] #right-top

        if rec2[0]>rec1[2] or rec1[0]>rec2[2]:
            return False
        elif rec1[1]>rec2[3] or rec2[1]>rec1[3]:
            return False
        else:
            max_x1 = [rec1[0],rec1[2],rec2[0],rec2[2]]
            max_x1.sort()
            x = max_x1[2]-max_x1[0]-max_x1[1]

            max_y1 = [rec1[1],rec1[3],rec2[1],rec2[3]]
            max_y1.sort()
            y = max_y1[2]-max_y1[0]-rec2[1]

            Aera = x*y
            if Aera == 0:
                return False
            else:
                return True

rec1 = [0,0,1,1]
rec2 = [1,0,2,1]
solution = Solution()
print solution.rectangle(rec1,rec2)

#方法二
solution: 计算它们的坐标的距离,若x方向有相交,则(x4-x1)(x2-x3)应该大于0,y轴同理

class Solution(object):
    def isRectangleOverlap(self, rec1, rec2):
        """
        :type rec1: List[int]
        :type rec2: List[int]
        :rtype: bool
        """
        x1, y1, x2, y2 = rec1
        x3, y3, x4, y4 = rec2
        return (x4 - x1) * (x2 - x3) > 0 and (y4 - y1) * (y2 - y3) > 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值