|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +# Given a binary matrix A, we want to flip the image horizontally, |
| 5 | +# then invert it, and return the resulting image. |
| 6 | +# |
| 7 | +# To flip an image horizontally means that each row of the image is reversed. |
| 8 | +# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. |
| 9 | +# |
| 10 | +# To invert an image means that each 0 is replaced by 1, and each 1 is |
| 11 | +# replaced by 0. |
| 12 | +# For example, inverting [0, 1, 1] results in [1, 0, 0]. |
| 13 | +# |
| 14 | +# Example 1: |
| 15 | +# |
| 16 | +# Input: [[1,1,0],[1,0,1],[0,0,0]] |
| 17 | +# Output: [[1,0,0],[0,1,0],[1,1,1]] |
| 18 | +# Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. |
| 19 | +# Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] |
| 20 | +# Example 2: |
| 21 | +# |
| 22 | +# Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] |
| 23 | +# Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] |
| 24 | +# Explanation: First reverse each row: |
| 25 | +# [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. |
| 26 | +# Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] |
| 27 | +# |
| 28 | +# Notes: |
| 29 | +# 1. 1 <= A.length = A[0].length <= 20 |
| 30 | +# 2. 0 <= A[i][j] <= 1 |
| 31 | + |
| 32 | +try: |
| 33 | + xrange # Python 2 |
| 34 | +except NameError: |
| 35 | + xrange = range # Python 3 |
| 36 | + |
| 37 | + |
| 38 | +class Solution(object): |
| 39 | + def flipAndInvertImage(self, A): |
| 40 | + """ |
| 41 | + :type A: List[List[int]] |
| 42 | + :rtype: List[List[int]] |
| 43 | + """ |
| 44 | + for row in A: |
| 45 | + for i in xrange((len(row)+1) // 2): |
| 46 | + row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 |
| 47 | + return A |
0 commit comments