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{}
}
相关推荐
liurunlin8882 小时前
Go环境搭建(vscode调试)
开发语言·vscode·golang
memcpy03 小时前
LeetCode 1456. 定长子串中元音的最大数目【定长滑窗模板题】中等
算法·leetcode·职场和发展
玛丽莲茼蒿3 小时前
LeetCode hot100【相交链表】【简单】
算法·leetcode·职场和发展
wen__xvn3 小时前
力扣模拟题刷题
算法·leetcode
不要秃头的小孩3 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
We་ct4 小时前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发
Navigator_Z4 小时前
LeetCode //C - 990. Satisfiability of Equality Equations
c语言·算法·leetcode
添尹5 小时前
Go语言基础之流程控制
golang
添尹5 小时前
Go语言基础之基本数据类型
开发语言·后端·golang
lightqjx6 小时前
【算法】前缀和
c++·算法·leetcode·前缀和