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{}
}
相关推荐
Swift社区1 小时前
Swift 解 LeetCode 320:一行单词有多少种缩写可能?用回溯找全解
开发语言·leetcode·swift
YuTaoShao11 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
简佐义的博客12 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
恋喵大鲤鱼16 小时前
Golang 运算符
golang·运算符
weixin_4373982116 小时前
转Go学习笔记(2)进阶
服务器·笔记·后端·学习·架构·golang
ac.char17 小时前
Golang读取ZIP压缩包并显示Gin静态html网站
golang·html·gin
Cxzzzzzzzzzz18 小时前
.golangci.yml文件配置
golang
百年孤独_19 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
算法_小学生19 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展