519.random-flip-matrix.go 800 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. type Solution struct {
  2. m map[int]int
  3. size int
  4. rows int
  5. cols int
  6. }
  7. func Constructor(n_rows int, n_cols int) Solution {
  8. return Solution{
  9. m: make(map[int]int),
  10. size: n_rows * n_cols,
  11. rows: n_rows,
  12. cols: n_cols,
  13. }
  14. }
  15. func (this *Solution) Flip() []int {
  16. idx := rand.Intn(this.size)
  17. i := idx
  18. this.size--
  19. if val, ok := this.m[idx]; ok {
  20. idx = val
  21. } // The trick is very important!
  22. if val, ok := this.m[this.size]; ok {
  23. this.m[i] = val
  24. } else {
  25. this.m[i] = this.size
  26. }
  27. return []int{idx / this.cols, idx % this.cols}
  28. }
  29. func (this *Solution) Reset() {
  30. this.m = make(map[int]int)
  31. this.size = this.rows * this.cols
  32. }
  33. /**
  34. * Your Solution object will be instantiated and called as such:
  35. * obj := Constructor(n_rows, n_cols);
  36. * param_1 := obj.Flip();
  37. * obj.Reset();
  38. */