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{}
}
相关推荐
lvwangshu3 小时前
CF1882D Tree XOR 题解
动态规划·题解·贪心·dp·树形dp·换根dp·性质题·思维好题·推导题
文丑颜不良啊4 小时前
LeetCode201~225题目解析
java·leetcode
Nil2088 小时前
LeetCode 283移动零
数据结构·算法·leetcode
文丑颜不良啊9 小时前
LeetCode226~250题目解析
java·leetcode
浮尘笔记11 小时前
我用 Go 写了个手机端「远程 AI 开发控制台」(开源)
人工智能·智能手机·golang
microrain13 小时前
专业版守核心,企业版做增量:SagooIoT 的跨模块能力出口
物联网·架构·golang·sagooiot
wenyq714 小时前
LeetCode 123. Best Time to Buy and Sell Stock III
leetcode
紧跟先前的步伐15 小时前
Go AI Agent 实战 04|Prompt 与消息角色:System、User、Assistant
人工智能·golang·prompt
念何架构之路15 小时前
go-grpc逻辑架构图
开发语言·后端·golang
FfHUCisI15 小时前
Linux 网络 IO 模型演进与 Epoll 内部机制
golang