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{}
}
相关推荐
Swift社区2 小时前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato2 小时前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
巴里巴气3 小时前
第15题 三数之和
数据结构·算法·leetcode
一根甜苦瓜3 小时前
Go语言Slice的一道骚题
开发语言·后端·golang
驰羽4 小时前
[GO]Go语言泛型详解
开发语言·golang·xcode
NPE~4 小时前
[手写系列]Go手写db — — 第五版(实现数据库操作模块)
开发语言·数据库·后端·golang·教程·手写系列·手写数据库
西阳未落4 小时前
LeetCode——双指针(进阶)
c++·算法·leetcode
熬了夜的程序员5 小时前
【LeetCode】69. x 的平方根
开发语言·算法·leetcode·职场和发展·动态规划
Swift社区14 小时前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt55555555555515 小时前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展