classSolution { publicintfirstCompleteIndex(int[] arr, int[][] mat) { intn= mat.length, m = mat[0].length; Map<Integer, int[]> map = newHashMap<>(); for (inti=0; i < n; i++) { for (intj=0; j < m; j++) { map.put(mat[i][j], newint[]{i, j}); } } int[] c1 = newint[n], c2 = newint[m]; for (inti=0; i < n * m; i++) { int[] info = map.get(arr[i]); intx= info[0], y = info[1]; if (++c1[x] == m || ++c2[y] == n) return i; } return -1; // never } }
C++ 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intfirstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat){ int n = mat.size(), m = mat[0].size(); unordered_map<int, pair<int, int>> map; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { map[mat[i][j]] = make_pair(i, j); } } vector<int> c1(n), c2(m); for (int i = 0; i < n * m; i++) { pair<int, int> info = map[arr[i]]; int x = info.first, y = info.second; if (++c1[x] == m || ++c2[y] == n) return i; } return-1; // never } };
Python 代码:
1 2 3 4 5 6 7 8 9 10
classSolution: deffirstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int: n, m = len(mat), len(mat[0]) mapping = {mat[i][j]: (i, j) for i inrange(n) for j inrange(m)} c1, c2 = [0] * n, [0] * m for i inrange(n * m): x, y = mapping[arr[i]] c1[x], c2[y] = c1[x] + 1, c2[y] + 1 if c1[x] == m or c2[y] == n: return i return -1# never
TypeScript 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
functionfirstCompleteIndex(arr: number[], mat: number[][]): number { const n = mat.length, m = mat[0].length; constmap: { [key: number]: [number, number] } = {}; for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { map[mat[i][j]] = [i, j]; } } const c1 = newArray(n).fill(0), c2 = newArray(m).fill(0); for (let i = 0; i < n * m; i++) { const [x, y] = map[arr[i]]; if (++c1[x] == m || ++c2[y] === n) return i; } return -1; // never };