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{}
}
相关推荐
记得早睡~6 分钟前
leetcode73-矩阵置零
数据结构·leetcode·矩阵
爱coding的橙子28 分钟前
每日算法刷题Day27 6.9:leetcode二分答案2道题,用时1h20min
算法·leetcode·职场和发展
朱颜辞镜花辞树‎2 小时前
Go爬虫开发学习记录
爬虫·学习·golang
圈圈编码7 小时前
LeetCode Hot100刷题——合并两个有序链表
java·数据结构·算法·leetcode·链表
岁忧7 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 下
sql·leetcode·正则表达式
onlooker66668 小时前
Go 语言底层(四) : 深入 Context 上下文
开发语言·数据库·golang
roman_日积跬步-终至千里8 小时前
【Go语言基础【5】】运算符基础
golang
不7夜宵12 小时前
力扣热题100 k个一组反转链表题解
算法·leetcode·链表