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 submissions
for Flipping an Image. Memory Usage: 35.1 MB, less than 48.85% of
JavaScript online submissions for Flipping an Image.
  1. 其他解法:

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]做倒序, 再两次遍历。

  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.


lllluull
135 声望9 粉丝