Golang | Leetcode Golang题解之第519题随机翻转矩阵

题目:

题解:

Go 复制代码
type Solution struct {
    m, n, total int
    mp          map[int]int
}

func Constructor(m, n int) Solution {
    return Solution{m, n, m * n, map[int]int{}}
}

func (s *Solution) Flip() (ans []int) {
    x := rand.Intn(s.total)
    s.total--
    if y, ok := s.mp[x]; ok { // 查找位置 x 对应的映射
        ans = []int{y / s.n, y % s.n}
    } else {
        ans = []int{x / s.n, x % s.n}
    }
    if y, ok := s.mp[s.total]; ok { // 将位置 x 对应的映射设置为位置 total 对应的映射
        s.mp[x] = y
    } else {
        s.mp[x] = s.total
    }
    return
}

func (s *Solution) Reset() {
    s.total = s.m * s.n
    s.mp = map[int]int{}
}
相关推荐
落霞的思绪33 分钟前
基于Go开发的矢量瓦片服务器——pg_tileserv
开发语言·后端·golang
卿雪38 分钟前
Redis 数据持久化:RDB和 AOF 有什么区别?
java·数据库·redis·python·mysql·缓存·golang
巴塞罗那的风40 分钟前
经典Agent架构实战之反思模型(Reflection)
后端·语言模型·golang
sin_hielo1 小时前
leetcode 1523
数据结构·算法·leetcode
倔强菜鸟1 小时前
2025.11.21-GO语言入门(一)
开发语言·后端·golang
风生u1 小时前
Go: Gin的用法
golang·xcode·gin
小龙报1 小时前
【算法通关指南:算法基础篇(三)】一维差分专题:1.【模板】差分 2.海底高铁
android·c语言·数据结构·c++·算法·leetcode·visual studio
小白程序员成长日记1 小时前
2025.12.07 力扣每日一题
算法·leetcode·职场和发展
风生u2 小时前
Go的并发(协程)
开发语言·后端·golang
米花町的小侦探2 小时前
Ubuntu安装多版本golang
linux·ubuntu·golang