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{}
}
相关推荐
·云扬·5 小时前
【Leetcode hot 100】101.对称二叉树
算法·leetcode·职场和发展
silver98866 小时前
再谈golang的sql链接dsn
mysql·golang
睡不醒的kun10 小时前
leetcode算法刷题的第三十二天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
刘媚-海外14 小时前
Go语言开发AI应用
开发语言·人工智能·golang·go
deepwater_zone14 小时前
Go语言核心技术
后端·golang
共享家952715 小时前
经典动态规划题解
算法·leetcode·动态规划
1白天的黑夜116 小时前
栈-844.比较含退格的字符串-力扣(LeetCode)
c++·leetcode·
二哈不在线17 小时前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划
Swift社区18 小时前
LeetCode 378 - 有序矩阵中第 K 小的元素
算法·leetcode·矩阵