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{}
}
相关推荐
爆打维c2 小时前
01BFS算法(例题:网格传送门旅游)
c语言·c++·python·算法·leetcode·广度优先
像素猎人2 小时前
力扣:面试题16.01.交换数字
c++·算法·leetcode·面试
We་ct4 小时前
LeetCode 58. 最后一个单词的长度:两种解法深度剖析
前端·算法·leetcode·typescript
小袁顶风作案4 小时前
leetcode力扣——452. 用最少数量的箭引爆气球
学习·算法·leetcode·职场和发展
爱编码的傅同学5 小时前
【今日算法】LeetCode 25.k个一组翻转链表 和 43.字符串相乘
算法·leetcode·链表
摸个小yu5 小时前
【力扣LeetCode热题h100】哈希、双指针、滑动窗口
算法·leetcode·哈希算法
We་ct6 小时前
LeetCode 12. 整数转罗马数字:从逐位实现到规则复用优化
前端·算法·leetcode·typescript
sin_hielo6 小时前
leetcode 3510
数据结构·算法·leetcode
Object~6 小时前
7.Go语言中的slice
开发语言·后端·golang
历程里程碑7 小时前
哈希3 : 最长连续序列
java·数据结构·c++·python·算法·leetcode·tornado