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{}
}
相关推荐
二楼后座。19 分钟前
Golang操作MySQL json字段优雅写法
mysql·golang·json
??tobenewyorker1 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
贝塔西塔1 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
熬了夜的程序员4 小时前
【华为机试】HJ61 放苹果
算法·华为·面试·golang
呆呆的小鳄鱼4 小时前
leetcode:HJ18 识别有效的IP地址和掩码并进行分类统计[华为机考][字符串]
算法·leetcode·华为
zstar-_5 小时前
【算法笔记】7.LeetCode-Hot100-图论专项
笔记·算法·leetcode
亚洲第一中锋_哈达迪5 小时前
详解缓存淘汰策略:LRU
后端·缓存·golang
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 209. 长度最小的子数组(双指针)
java·c++·算法·leetcode·面试·go
剪一朵云爱着12 小时前
力扣2438. 二的幂数组中查询范围内的乘积
算法·leetcode