首页 > 其他分享 >LeetCode Top Interview 150 - Matrix

LeetCode Top Interview 150 - Matrix

时间:2025-01-11 21:32:43浏览次数:3  
标签:150 set matrix Top List range board Interview row

This is merely my personal review of all the typical problems that constitute the mindset for Data Structures and Algorithms (DSA). python solution provided

For the remaining types of problems, please refer to my channel.

everecursion-CSDN博客everecursion关注python,github,chatgpt领域.https://blog.csdn.net/gcsyymm


Valid Sudoku

Valid Sudokuicon-default.png?t=O83Ahttps://leetcode.cn/problems/valid-sudoku/

 Difficulty:MED

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        # check each row is valid
        for row in board:
            row_set = set()
            for num in row:
                if num != ".":
                    if num in row_set:
                        return False
                    row_set.add(num)

        # check each col is valid
        for c in range(9):
            col_set = set()
            for r in range(9):
                cur = board[r][c]
                if cur != ".":
                    if cur in col_set:
                        return False
                    col_set.add(cur)

        # check each box is valid
        for i in range(0, 9, 3):
            for j in range(0, 9, 3):
                box_set = set()
                for x in range(i, i + 3):
                    for y in range(j, j + 3):
                        cur = board[x][y]
                        if cur != ".":
                            if cur in box_set:
                                return False
                            box_set.add(cur)

        return True

Spiral Matrix

Spiral Matrixicon-default.png?t=O83Ahttps://leetcode.cn/problems/spiral-matrix/Difficulty:MED

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        # directions vectors (row movement, col movement)
        directions = (0, 1), (1, 0), (0, -1), (-1, 0)
        # row index, col index, direction index
        i = j = di = 0
        res = []
        for _ in range(len(matrix) * len(matrix[0])):
            res.append(matrix[i][j])
            matrix[i][j] = "visited"
            # check if next movement is valid
            next_i, next_j = i + directions[di][0], j + directions[di][1]
            # if it is not valid, change direction index
            if (
                not 0 <= next_i < len(matrix)
                or not 0 <= next_j < len(matrix[0])
                or matrix[next_i][next_j] == "visited"
            ):
                di = (di + 1) % 4
            i += directions[di][0]
            j += directions[di][1]
        return res

Rotate Image

Rotate Imageicon-default.png?t=O83Ahttps://leetcode.cn/problems/rotate-image/

 Difficulty:MED

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        # rotate from diagnal first
        for i in range(len(matrix)):
            for j in range(i):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        # then rotate horizontally;
        for i in range(len(matrix)):
            matrix[i] = matrix[i][::-1]
        # IMPORTANT: YOU CANT ROTATE HORIZONTAL LIKE:
        # for row in matrix:
        #   row = row[::-1]
        # bc list is mutable and you are just edit the reference to
        # the local variable, the original matrix is not changed

 Game of Life

Game of Lifeicon-default.png?t=O83Ahttps://leetcode.cn/problems/game-of-life/ Difficulty:MED

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """

        for i in range(len(board)):
            for j in range(len(board[0])):
                live_nbrs = 0
                # calculating living neighbours
                for ni in range(i - 1, i + 2):
                    for nj in range(j - 1, j + 2):
                        if (
                            not (ni == i and nj == j)
                            and 0 <= ni < len(board)
                            and 0 <= nj < len(board[0])
                            and abs(board[ni][nj]) == 1
                        ):
                            live_nbrs += 1
                # using abs(val)==1 determine it is living at current
                if board[i][j] == 1 and not (2 <= live_nbrs <= 3):
                    board[i][j] = -1
                # using val > 0 determine next state is living
                if board[i][j] == 0 and live_nbrs == 3:
                    board[i][j] = 2

        # change each cell to its next state
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] > 0:
                    board[i][j] = 1
                else:
                    board[i][j] = 0

For the remaining types of problems, please refer to my channel. 

everecursion-CSDN博客everecursion关注python,github,chatgpt领域.https://blog.csdn.net/gcsyymm

标签:150,set,matrix,Top,List,range,board,Interview,row
From: https://blog.csdn.net/gcsyymm/article/details/145002609

相关文章

  • 施耐德 三菱 西门子PLC 以太网口S7-1200/1500系列通讯协议解析说明文档
       资料参考链接:https://item.taobao.com/item.htm?abbucket=1&id=766532329733&ns=1&pisk=g0VseN0PDhxsC5j0KlbEVm4PVjhjhw5yfEgYrrdwkfhtDJaucc7cIfyIckEIXC7GIxnbjfH0QmoZcja0VwSPa_zgSjcR4g5yCEod7bAxWqKqv23rGVC1T97TSjcA4eRAU_ag2s7Opd3xJwgqlFnYDAhpvVoKWd......
  • Python 常用 150 个英语单词
    一、交互式环境与print输出1、print:打印/输出2、coding:编码3、syntax:语法4、error:错误5、invalid:无效6、identifier:名称/标识符7、character:字符二、字符串的操作1、user:用户2、name:姓名/名称3、attribute:字段/属性4、value:值5、key:键三、重复/转换/替换/原始字符......
  • 【漫话机器学习系列】043.提前停止训练(Early Stopping)
    提前停止训练(EarlyStopping)提前停止(EarlyStopping)是一种在训练机器学习模型(尤其是深度学习模型)时常用的正则化技术,用于防止过拟合并提升模型的泛化能力。它通过监控验证集的性能,在性能不再提高或开始下降时终止训练,从而选择性能最佳的模型。工作原理提前停止的基本思想......
  • 【解决方案】Windows 清理 C 盘,拒绝让 Desktop App 在 C 盘拉屎(配置/缓存/数据/预训练
    Windows有多磁盘管理,那又如何,许多程序为了节省上行带宽流量,会将大量数据/预训练模型默认下载到我们C盘的某个位置,动辄就是几GB甚至几十GB,有的干脆没有提供修改入口。安装系统时我特意为C盘留出200GB的空间,后来从职业装机那边了解到,对于个人和工作使用已经算非常大了。......
  • NFCAdapter.stopDiscovery
    NFCAdapter.stopDiscovery(Objectobject)基础库2.11.2开始支持,低版本需做兼容处理。以Promise风格调用:不支持小程序插件:支持微信iOS版:不支持微信Android版:支持相关文档:近场通信(NFC)功能描述参数Objectobject属性类型默认值必填说明suc......
  • 百度Android最新150道面试题及参考答案 (中)
    Android中一个View的显示渲染过程,自定义View的时候需要避免什么操作?一、View的显示渲染过程测量(Measure)阶段这个阶段是View渲染的第一步。父容器会调用子View的measure()方法来确定子View的大小。measure()方法会传入两个参数,即MeasureSpec(测量规格),它包含......
  • LeetCode Top Interview 150 - Hashmap
    Inthischapter,thereareseveralproblemsthatareratherstraightforwardandpossessnumerousapproaches.Asaresult,thosequestionshavebeenomittedherein.GroupAnagrams GroupAnagramshttps://leetcode.cn/problems/group-anagrams/Difficulty:MED......
  • 深入学习Topic Exchange交换机
            在消息队列系统中,交换机(Exchange)作为消息分发中心,负责将生产者发送的消息根据路由规则路由到一个或多个队列中。TopicExchange(主题交换机)是其中一种强大的交换机类型,它通过路由键(RoutingKey)的通配符匹配,提供了灵活的消息路由机制。本文将深入探讨TopicExcha......
  • Linux 运维必备 150 个命令汇总
    本文章盘点了Linux运维必备150个命令,可配合Linuxcool网站使用。线上查询及帮助命令man:全拼manual,用来查看系统中自带的各种参考手册。help:用于显示shell内部命令的帮助信息。文件和目录操作命令ls:全拼list,列出目录的内容及其内容属性信息。cd:全拼changedirectory,切换当......
  • w150基于springboot的贸易行业crm系统
    ......