LeetCode - Algorithms - 1275. Find Winner on a Tic Tac Toe Game

Problem

1275. Find Winner on a Tic Tac Toe Game

Tic-tac-toe

Java

my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public String tictactoe(int[][] moves) {
final int len = moves.length;
List<int[]> listX = new ArrayList<int[]>();
List<int[]> listO = new ArrayList<int[]>();
for (int i = 0; i < len; i++) {
if (i % 2 == 0)
listX.add(moves[i]);
else
listO.add(moves[i]);
}
String r = "";
if (hasWin(listX))
r = "A";
else if (hasWin(listO))
r = "B";
else if (len == 9)
r = "Draw";
else
r = "Pending";
return r;
}

private boolean realContain(List<int[]> list, int[][] arr) {
boolean b = true;
for (int i = 0; i < arr.length; i++) {
boolean b2 = false;
for (int j = 0; j < list.size(); j++) {
b2 = b2 || ((arr[i][0] == list.get(j)[0]) && (arr[i][1] == list.get(j)[1]));
}
b = b && b2;
}
return b;
}

private boolean hasWin(List<int[]> list) {
int[][] a1 = {{0, 0},{0, 1},{0, 2}};
int[][] a2 = {{1, 0},{1, 1},{1, 2}};
int[][] a3 = {{2, 0},{2, 1},{2, 2}};
int[][] a4 = {{0, 0},{1, 0},{2, 0}};
int[][] a5 = {{0, 1},{1, 1},{2, 1}};
int[][] a6 = {{0, 2},{1, 2},{2, 2}};
int[][] a7 = {{0, 0},{1, 1},{2, 2}};
int[][] a8 = {{0, 2},{1, 1},{2, 0}};
boolean r = realContain(list, a1) || realContain(list, a2) || realContain(list, a3)
|| realContain(list, a4) || realContain(list, a5) || realContain(list, a6)
|| realContain(list, a7) || realContain(list, a8);
return r;
}
}

Submission Detail

  • 100 / 100 test cases passed.
  • Runtime: 2 ms, faster than 8.21% of Java online submissions for Find Winner on a Tic Tac Toe Game.
  • Memory Usage: 38.9 MB, less than 6.40% of Java online submissions for Find Winner on a Tic Tac Toe Game.