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{}
}
相关推荐
特立独行的猫a1 小时前
仓颉语言UI开发实战:我用仓颉写了个桌面版力扣
算法·leetcode·ui·tauri·仓颉·cj-tarui
茉莉玫瑰花茶1 小时前
GO [ 标准库 ]
开发语言·后端·golang
y1su1 小时前
Leetcode 动态规划 模板
java·数据结构·算法·leetcode·动态规划
All for pursuit.2 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
All for pursuit.4 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
mmmmath_34 小时前
LeetCode.101.对称二叉树
数据结构·leetcode
mmmmath_39 小时前
LeetCode.637.二叉树的层平均值
算法·leetcode
Tisfy9 小时前
LeetCode 2913.子数组不同元素数目的平方和 I:第一题先常数很大的O(n^2)
算法·leetcode·题解·模拟·暴力
木井巳11 小时前
【动态规划】三步问题
java·算法·leetcode·动态规划·推荐算法
蛋蛋的就会顺顺的20 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣