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{}
}
相关推荐
踩坑记录7 小时前
leetcode hot100 79. 单词搜索 medium 递归回溯
leetcode
Rhystt8 小时前
代码随想录第二十六天|669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树
数据结构·c++·算法·leetcode
源代码•宸9 小时前
简版抖音项目——项目需求、项目整体设计、Gin 框架使用、视频模块方案设计、用户与鉴权模块方案设计、JWT
经验分享·后端·golang·音视频·gin·jwt·gorm
nix.gnehc9 小时前
深入浅出 Go 内存管理(二):预分配、GC 与内存复用实战
golang
creator_Li9 小时前
Golang的Channel
golang·channel
TracyCoder12310 小时前
LeetCode Hot100(57/100)——5. 最长回文子串
算法·leetcode·职场和发展
WZ1881046386910 小时前
LeetCode第20题
算法·leetcode
吕司10 小时前
LeetCode Hot Code——三数之和
数据结构·算法·leetcode
YGGP10 小时前
【Golang】LeetCode 54. 螺旋矩阵
算法·leetcode·矩阵
TracyCoder12311 小时前
LeetCode Hot100(58/100)——138. 随机链表的复制
leetcode·链表