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{}
}
相关推荐
Tisfy8 小时前
LeetCode 2540.最小公共值:双指针(O(m+n))
算法·leetcode·题解·双指针
geovindu12 小时前
go: Semaphore Pattern
开发语言·后端·设计模式·golang·企业级信号量模式
运筹vivo@13 小时前
LeetCode 2405. 子字符串的最优划分
c++·算法·leetcode·职场和发展·哈希表
sheeta199814 小时前
LeetCode 每日一题笔记 日期:2026.05.19 题目:2540. 最小公共值
笔记·leetcode·排序算法
dusk_star15 小时前
go语言--笔记--封装、组合(继承)
笔记·golang
sheeta199817 小时前
LeetCode 每日一题笔记 日期:2026.05.16 题目:154. 寻找旋转排序数组中的最小值 II
笔记·算法·leetcode
姚不倒17 小时前
Go 语言基础入门:从零到实战,一篇文章掌握核心语法
云原生·golang
阿Y加油吧19 小时前
两道位运算 / 摩尔投票经典题复盘:只出现一次的数字 & 多数元素
数据结构·算法·leetcode
XMYX-020 小时前
33 - Go 文本模板 template:从入门到原理深挖
golang·正则表达式
承渊政道21 小时前
【贪心算法】(经典实战应用解析(五):单调递增的数字、坏了的计算器、合并区间、⽆重叠区间、⽤最少数量的箭引爆⽓球)
数据结构·c++·leetcode·贪心算法·排序算法·动态规划·哈希算法