leetcode5: 矩阵反转

46次阅读

共计 1687 个字符,预计需要花费 5 分钟才能阅读完成。

1. 题目:Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. 实际就是先把子数组倒序,再把 1 和 0 互换。例子 1:
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
例子 2:
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
2. 我的解法:Javascript
var flipAndInvertImage = function(A) {
return A.map(a => a.reverse().map(v => v? 0: 1)
)
};
Runtime: 68 ms, faster than 94.99% of JavaScript online submissionsfor Flipping an Image. Memory Usage: 35.1 MB, less than 48.85% ofJavaScript online submissions for Flipping an Image.
其他解法:
Python
class Solution(object):
def flipAndInvertImage(self, A):
return [[1-i for i in row[::-1]] for row in A]
1- i 功能 1 和 0 的转化,row[::-1] 做倒序,再两次遍历。
扩展知识:
var flipAndInvertImage = function(A) {
return A.map(row => row.reverse().map(num => num^1));

}; 这里用到了按位异或运算符 ^ 参与运算的两个值,如果两个相应位相同,则结果为 0,否则为 1。即:0^0=0,1^0=1,0^1=1,1^1=0
例如:10100001^00010001=10110000
0^0=0,0^1=1 0 异或任何数=任何数
1^0=1,1^1=0 1 异或任何数-任何数取反
任何数异或自己=把自己置 0
(1) 按位异或可以用来使某些特定的位翻转,如对数 10100001 的第 2 位和第 3 位翻转,可以将数与 00000110 进行按位异或运算。
10100001^00000110=10100111 //1010 0001 ^ 0x06 = 1010 0001 ^ 6
(2) 通过按位异或运算,可以实现两个值的交换,而不必使用临时变量。例如交换两个整数 a,b 的值,可通过下列语句实现:
    a=10100001,b=00000110
    a=a^b;//a=10100111
    b=b^a;//b=10100001
    a=a^b;//a=00000110
(3) 异或运算符的特点是:数 a 两次异或同一个数 b(a=a^b^b)仍然为原值 a.

正文完
 0