leetcode 832. Flipping an Image(C++)

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].

Example 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]]

Example 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]]

Notes:

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

题目大意:

  给定一个二维数组,将数组的每一个元素转置,再将0和1互换。

解题思路:

  STL有reverse方法可以直接调用,01互换直接用异或即可。

解题代码:

class Solution {
public:
    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
        for(size_t i = 0; i < A.size(); ++i){
            reverse(A[i].begin(), A[i].end());
            for(size_t j = 0; j < A[i].size(); ++j)
                A[i][j] = A[i][j]^1;
        }
        return A;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,200评论 3 20
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,418评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,487评论 0 13
  • 突然感觉时间过的真快,觉得不留点什么自己也消失的好快,开始变得不认识自己。因为国庆的原因,大家都出去玩了,留下的我...
    书信都好漫阅读 218评论 0 0
  • 来自张伟权践行第20天作业:《你觉得这13条,那条对你有用》 老张憋了大招终于发出来了。 说真的,这13条对我而言...
    天刀笑剑钝阅读 331评论 0 2