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{}
}
相关推荐
Forever Nore1 小时前
LeetCode 13 罗马数字转整数 - 按规则处理
linux·服务器·leetcode
旖旎夜光2 小时前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
ZC跨境爬虫3 小时前
LeetCode 27. 移除元素(双指针详解 + Java Python 多解法对比)
java·python·leetcode
圣殿骑士-Khtangc4 小时前
Go错误处理最佳实践进阶从error到panic的完整指南
golang
运维开发笔记5 小时前
3.6 Go defer 语句学习笔记
golang
LuminousCPP6 小时前
单链表专题(四)-刷题复盘篇-LeetCode 138 随机链表复制|原地拷贝法突破复杂指针操作
数据结构·笔记·算法·leetcode·链表
存在morning6 小时前
【Python 开发实践 一】Python vs Go vs Java 三门语言对比
java·python·golang
Forever Nore6 小时前
LeetCode 14 最长公共前缀 - 纵向扫描
linux·服务器·leetcode
圣保罗的大教堂6 小时前
leetcode 3090. 每个字符最多出现两次的最长子字符串 简单
leetcode
圣殿骑士-Khtangc18 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang