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{}
}
相关推荐
karatttt14 分钟前
用go从零构建写一个RPC(仿gRPC,tRPC)--- 版本1
后端·qt·rpc·架构·golang
web守墓人3 小时前
【go语言】window环境从源码编译go
开发语言·后端·golang
画个大饼10 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
Demons_kirit15 小时前
Leetcode 2845 题解
算法·leetcode·职场和发展
Yeats_Liao17 小时前
Go 语言 TCP 端口扫描器实现与 Goroutine 池原理
开发语言·tcp/ip·golang
我的golang之路果然有问题17 小时前
速成GO访问sql,个人笔记
经验分享·笔记·后端·sql·golang·go·database
Wendy_robot18 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.18 小时前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
Y1nhl20 小时前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展
前端 贾公子20 小时前
详解 LeetCode 第 242 题 - 有效的字母组
算法·leetcode·职场和发展