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{}
}
相关推荐
yaoh.wang3 小时前
力扣(LeetCode) 88: 合并两个有序数组 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
apocelipes3 小时前
从源码角度解析C++20新特性如何简化线程超时取消
c++·性能优化·golang·并发·c++20·linux编程
LYFlied3 小时前
【每日算法】 LeetCode 56. 合并区间
前端·算法·leetcode·面试·职场和发展
XFF不秃头6 小时前
力扣刷题笔记-全排列
c++·笔记·算法·leetcode
菜鸟233号6 小时前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode
yaoh.wang7 小时前
力扣(LeetCode) 100: 相同的树 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
SadSunset7 小时前
力扣题目142. 环形链表 II的解法分享,附图解
算法·leetcode·链表
iAkuya8 小时前
(leetcode)力扣100 19螺旋矩阵(方向数组/边界把控)
算法·leetcode·矩阵
爱编程的小吴8 小时前
【力扣练习题】热题100道【哈希】 最长连续序列
算法·leetcode·职场和发展
Rinai_R9 小时前
Go 的调度模型
开发语言·后端·golang