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{}
}
相关推荐
阿俊-全栈开发8 小时前
扩展设计解析:LikeShop Go 版商城营销活动的插件化扩展设计思路
开发语言·微服务·golang·likeshop·likeshop源码
Nazarick13 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴13 小时前
斐波那契数列题解
算法·leetcode
microrain16 小时前
请求进来,先认人再认权
物联网·golang·鉴权·sagooiot
Tisfy16 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
Navigator_Z20 小时前
LeetCode //C - 1332. Remove Palindromic Subsequences
c语言·算法·leetcode
Nazarick21 小时前
力扣LeetCode热题(3)
java·算法·leetcode·贪心算法
Rain的Java大神之路21 小时前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试
码途行者1 天前
每天10分钟学Go:第31课 原子操作与互斥锁
开发语言·后端·golang
o0o_-_1 天前
【golang/rust】rs-gopls 上手指南|安装、VS Code / Zed 配置与性能对比
开发语言·golang·rust