dengxinyi 6 年之前
父節點
當前提交
bd3a8e974b
共有 1 個文件被更改,包括 25 次插入5 次删除
  1. 25 5
      medium/519.random-flip-matrix.go

+ 25 - 5
medium/519.random-flip-matrix.go

@@ -1,17 +1,37 @@
 type Solution struct {
-	
+	m    map[int]int
+	size int
+	rows int
+	cols int
 }
 
 func Constructor(n_rows int, n_cols int) Solution {
-	
+	return Solution{
+		m:    make(map[int]int),
+		size: n_rows * n_cols,
+		rows: n_rows,
+		cols: n_cols,
+	}
 }
 
 func (this *Solution) Flip() []int {
-	
+	idx := rand.Intn(this.size)
+	i := idx
+	this.size--
+	if val, ok := this.m[idx]; ok {
+		idx = val
+	} // The trick is very important!
+	if val, ok := this.m[this.size]; ok {
+		this.m[i] = val
+	} else {
+		this.m[i] = this.size
+	}
+	return []int{idx / this.cols, idx % this.cols}
 }
 
-func (this *Solution) Reset()  {
-	
+func (this *Solution) Reset() {
+	this.m = make(map[int]int)
+	this.size = this.rows * this.cols
 }
 
 /**