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{}
}
相关推荐
veejaLiu19 分钟前
LeetCode 30.串联所有单词的子串
java·学习·算法·leetcode·职场和发展·刷题
安忘5 小时前
LeetCode-274.H 指数
算法·leetcode·职场和发展
xxxmmc5 小时前
Leetcode 160 Intersection of Two Linked Lists
算法·leetcode·双指针
维齐洛波奇特利(male)11 小时前
(暴力枚举 水题 长度为3的不同回文子序列)leetcode 1930
算法·leetcode·职场和发展
徐小黑ACG11 小时前
个人blog系统 前后端分离 前端js后端go
开发语言·前端·javascript·vue.js·golang
dapeng-大鹏11 小时前
Go语言中的错误处理与异常恢复:性能对比与实践思考
开发语言·后端·golang·错误处理
崔婉凝13 小时前
Ruby语言的工业物联网
开发语言·后端·golang
奔跑的废柴15 小时前
LeetCode 452. 用最少数量的箭引爆气球 java题解
java·算法·leetcode·贪心算法·贪心
宁懿妤15 小时前
Lua语言的网络编程
开发语言·后端·golang
行思理16 小时前
PHP、Java、Go、Python、Node.js、Ruby 写的接口,服务器承载量对比
java·golang·php