leetcode: 832 - Flipping an Image

前言

       我本科的数据结构与算法学得并不好,现在的记忆也比较模糊了,而对于算法工程师而言,编程思想和能力却是必不可少的,所以我决定从今天开始刷leetcode,计划是先从array、string、tree、linkedlist、math五个tag开始,按照easy到medium到hard的顺序(hard暂时先放过,这次以过知识点为主),以过年为期限系统实践一遍数据结构与算法。

      参考教材:《数据结构与算法》、《大话数据结构》、《算法 第4版》

      参考视频:《数据结构 -浙江大学MOOC》、《数据结构与算法 -清华邓俊辉MOOC》

题目描述

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. 简单实现

       思路很简单,首先定义两个空list用来接收处理好的矩阵和矩阵行,然后遍历二维矩阵的每一行,取出行内最末尾元素,将元素0/1翻转,然后添加到空list中,继续处理下一个元素,如此这样得到一行已经处理好的list,添加到用于返回的空list中,继续处理下一行。这个算法的复杂度是O(N^2),运行时间48ms,打败了97%的Python3解法。

class Solution:
    def flipAndInvertImage(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        output = []
        row = []
        for r in A:
            while len(r)>=1:
                g = r.pop()
                if g == 1:
                    g = 0
                elif g == 0:
                    g = 1
                row.append(g)
            output.append(row)
            row = []
        return output

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值