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{}
}
相关推荐
长安er11 分钟前
LeetCode 20/155/394/739/84/42/单调栈核心原理与经典题型全解析
数据结构·算法·leetcode·动态规划·
wadesir1 小时前
Go语言中高效读取数据(详解io包的ReadAll函数用法)
开发语言·后端·golang
yoke菜籽1 小时前
LeetCode——三指针
算法·leetcode·职场和发展
幺零九零零2 小时前
Golang-Swagger
开发语言·后端·golang
闲看云起4 小时前
LeetCode day3-最长连续序列
算法·leetcode
六毛的毛5 小时前
比较含退格的字符串
开发语言·python·leetcode
iAkuya5 小时前
(leetcode)力扣100 27合并两个有序链表(迭代/递归)
算法·leetcode·链表
nextvary5 小时前
cursort如何在不同项目下自动适配asdf安装的golang
golang·cursor·asdf
LYFlied6 小时前
【每日算法】LeetCode 5. 最长回文子串(动态规划)
数据结构·算法·leetcode·职场和发展·动态规划
Javis2116 小时前
【Go转型AI应用开发】01.Go+OpenAI原生SDK构建LLM-Client
golang·iphone·ai-native