又是涉及到均等概率的随机 ~ 用的题解区三叶的代码~写得是真的好!不论题目,但抄一遍代码都能觉得有收获! 维度转化 :并没有创造二维数组(太大了)。而是转化成一维的场景。双指针 :每次随机一个[0, m * n)的值,然后向左、向右查找第一个没访问过的值class  Solution  { int  m; int  n; Random  random =  new  Random ( ) ; Set < Integer > =  new  HashSet < > ( ) ;  public  Solution ( int  m,  int  n)  { this . m =  m; this . n =  n; } public  int [ ]  flip ( )  { int  toLeft =  random. nextInt ( m *  n) ,  toRight =  toLeft;  while ( toLeft >=  0  &&  set. contains ( toLeft) )  toLeft-- ; while ( toRight <  m *  n &&  set. contains ( toRight) )  toRight++ ; int  index =  toLeft >=  0  &&  ! set. contains ( toLeft)  ?  toLeft :  toRight;  set. add ( index) ; return  new  int [ ] { index /  n,  index %  n} ;  } public  void  reset ( )  { set. clear ( ) ; } 
} 
class  Solution  { int  m,  n; Set < Integer > =  new  HashSet < > ( ) ; Random  random =  new  Random ( ) ; public  Solution ( int  m,  int  n)  { this . m =  m; this . n =  n; } public  int [ ]  flip ( )  { int  toLeft =  random. nextInt ( m *  n) ,  toRight =  toLeft; while ( toLeft >=  0  &&  set. contains ( toLeft) )  toLeft-- ; while ( toRight <  m *  n &&  set. contains ( toRight) )  toRight++ ; int  index =  toLeft >=  0  &&  ! set. contains ( toLeft)  ?  toLeft :  toRight; set. add ( index) ; return  new  int [ ] { index /  n,  index %  n} ; } public  void  reset ( )  { set. clear ( ) ; } 
}