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{}
}
相关推荐
小刘不想改BUG1 小时前
LeetCode LCR 010 和为 K 的子数组 (Java)
java·算法·leetcode
{⌐■_■}2 小时前
【kafka】kafka概念,使用技巧go示例
golang·kafka·linq
小雅痞2 小时前
[Java][Leetcode middle] 12. 整数转罗马数字
java·linux·leetcode
Espresso Macchiato2 小时前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
Villiam_AY3 小时前
Go 后端中双 token 的实现模板
开发语言·后端·golang
緈福的街口14 小时前
【leetcode】2900. 最长相邻不相等子序列 I
算法·leetcode·职场和发展
进击的小白菜15 小时前
LeetCode 153. 寻找旋转排序数组中的最小值:二分查找法详解及高频疑问解析
数据结构·算法·leetcode
Chandler2416 小时前
Go语言 GORM框架 使用指南
开发语言·后端·golang·orm
wktomo17 小时前
GO语言学习(二)
学习·golang
緈福的街口17 小时前
【leetcode】144. 二叉树的前序遍历
算法·leetcode