• Leetcode 832.翻转图像


    1.题目描述

    给定一个二进制矩阵 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

    2.我的代码

    //卸去对C语言的兼容,加速执行
    /*static const auto KSpeedUp = [](){
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        return nullptr;
    }();*/
    
    class Solution {
    public:
        vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
            //翻转每一行,反转每一行
            for(auto& a : A){
                reverse(a);
                overturn(a);
            }
            return A;
            }
        
         //反转
        vector<int> overturn(vector<int>& nums){
                for(auto& c : nums){
                    c = (c==0)? 1 : 0;
                }
            return nums;
            }
        
        //翻转(逆序)
        vector<int> reverse(vector<int>& nums){
                int sz = nums.size();
                for(int i=0; i<=sz/2-1; ++i){
                    swap(nums[i],nums[sz-i-1]);
                }
            return nums;
        }
    };

    3.局部优化代码

    • reverse()函数支持对向量的翻转,无需自己造轮子;
    • 1变0,0变1的技巧:c = 1 - c;
    class Solution {
    public:
        vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
            //翻转每一行,反转每一行
            for(auto& a : A){
                reverse(a.begin(),a.end());//注意:使用迭代器调用
                overturn(a);
            }
            return A;
            }
        
         //反转
        vector<int> overturn(vector<int>& nums){
                for(auto& c : nums){
                    //c = (c==0)? 1 : 0;
                    c = 1-c;
                }
            return nums;
        }
    };

    4.Leetcode的置顶范例

    class Solution {
    public:
        vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
        if (A.empty()) return A;
        
        for (vector<int> &row : A)
        {
            reverse(row.begin(), row.end());//逆序每一行
            for_each(row.begin(), row.end(), [](int& x){x = 1^x; });//反转每一行 for_each遍历+lambda表达式
        }
        return A;
    }
    };

    参考资料:

    1.论C++11 中vector的N种遍历方法 (for_each遍历+Lambda函数)

  • 相关阅读:
    wcf 基本配置
    Config 代码片段
    常用的中文字体
    C++创建一个新的进程
    C++ 线程学习
    [C++]多线程: 教你写第一个线程
    C++ 多线程编程实例【2个线程模拟卖火车票的小程序】
    C++使用thread类多线程编程
    C++多线程编程(★入门经典实例★)
    C++ 多线程
  • 原文地址:https://www.cnblogs.com/paulprayer/p/10150673.html
Copyright © 2020-2023  润新知