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{}
}
相关推荐
运筹vivo@7 小时前
2657. 找到两个数组的前缀公共数组 | 难度:中等
算法·leetcode·职场和发展·哈希表
比特森林探险记8 小时前
go 语言中的context 解读和用法
开发语言·后端·golang
叶小鸡14 小时前
小鸡玩算法-力扣HOT100-动态规划(下)
算法·leetcode·动态规划
毅炼16 小时前
今日LeetCode 摸鱼打卡
java·算法·leetcode
m0_6294947316 小时前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒16 小时前
力扣HOT100(25)环形链表
算法·leetcode·链表
jieyucx18 小时前
从基础语法到面向对象:Go语言如何实现封装、继承与多态?
开发语言·后端·golang
littleschemer19 小时前
Go:实现游戏服务器网关
服务器·网关·游戏·golang
Controller-Inversion20 小时前
76. 最小覆盖子串
java·算法·leetcode
_日拱一卒20 小时前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展