LeetCode 832. 翻转图像(Python)

给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。

水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。

反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。

示例 1:

输入: [[1,1,0],[1,0,1],[0,0,0]]
输出: [[1,0,0],[0,1,0],[1,1,1]]
解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
         然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]


示例 2:

输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
         然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]


说明:

1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1

思路:利用元组实现数据交换的技巧;1,0交替可通过对其异或获得

class Solution(object):
    def flipAndInvertImage(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        # B = List[List[]]
        # 翻转每一行
        for line in A:
            for row_index in range(len(line)):
                if row_index < len(line)/2:
                    line[row_index], line[len(line) - row_index - 1] = line[len(line) - row_index - 1] , line[row_index]
                
                line[row_index] = line[row_index] ^ 1
                
    
        return A
                    
        
        
                    
            

此题解非常好: https://leetcode-cn.com/problems/flipping-an-image/solution/python3-duo-chong-jie-fa-xiang-jie-han-zui-duan-1x/

发布了88 篇原创文章 · 获赞 98 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/HNU_Csee_wjw/article/details/101537358