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{}
}
相关推荐
独自破碎E35 分钟前
二分查找-I
leetcode
千金裘换酒1 小时前
LeetCode 删除链表的倒数第N个结点
算法·leetcode
老鼠只爱大米2 小时前
LeetCode算法题详解 42:接雨水
leetcode·动态规划·双指针·单调栈·接雨水·雨水收集
AlenTech2 小时前
739. 每日温度 - 力扣(LeetCode)
算法·leetcode·职场和发展
老鼠只爱大米3 小时前
LeetCode算法题详解 11:盛最多水的容器
leetcode·面试题·双指针·盛最多水的容器·面积最大化
im_AMBER5 小时前
Leetcode 99 删除排序链表中的重复元素 | 合并两个链表
数据结构·笔记·学习·算法·leetcode·链表
源代码•宸6 小时前
Leetcode—1123. 最深叶节点的最近公共祖先【中等】
经验分享·算法·leetcode·职场和发展·golang·dfs
alphaTao6 小时前
LeetCode 每日一题 2026/1/5-2026/1/11
算法·leetcode
黎雁·泠崖7 小时前
二叉树知识体系全梳理:从基础到进阶一站式通关
c语言·数据结构·leetcode
源代码•宸7 小时前
Golang基础语法(go语言error、go语言defer、go语言异常捕获、依赖管理、Go Modules命令)
开发语言·数据库·后端·算法·golang·defer·recover