题目

类型:HashTable
image.png

解题思路

哈希表+Swap
image.png

代码

  1. class Solution {
  2. int m, n, cnt; // cnt 为剩余数个数,同时 cnt - 1 为区间右端点位置
  3. Map<Integer, Integer> map = new HashMap<>();
  4. Random random = new Random(300);
  5. public Solution(int _m, int _n) {
  6. m = _m; n = _n; cnt = m * n;
  7. }
  8. public int[] flip() {
  9. int x = random.nextInt(cnt--);
  10. int idx = map.getOrDefault(x, x);
  11. map.put(x, map.getOrDefault(cnt, cnt));
  12. return new int[]{idx / n, idx % n};
  13. }
  14. public void reset() {
  15. cnt = m * n;
  16. map.clear();
  17. }
  18. }
  19. /**
  20. * Your Solution object will be instantiated and called as such:
  21. * Solution obj = new Solution(m, n);
  22. * int[] param_1 = obj.flip();
  23. * obj.reset();
  24. */