classSolution: defcanFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: index = {p[0]: i for i, p inenumerate(pieces)} i = 0 while i < len(arr): if arr[i] notin index: returnFalse p = pieces[index[arr[i]]] if arr[i: i + len(p)] != p: returnFalse i += len(p) returnTrue
classSolution { publicbooleancanFormArray(int[] arr, int[][] pieces) { intn= arr.length, m = pieces.length; Map<Integer, Integer> index = newHashMap<Integer, Integer>(); for (inti=0; i < m; i++) { index.put(pieces[i][0], i); } for (inti=0; i < n;) { if (!index.containsKey(arr[i])) { returnfalse; } intj= index.get(arr[i]), len = pieces[j].length; for (intk=0; k < len; k++) { if (arr[i + k] != pieces[j][k]) { returnfalse; } } i = i + len; } returntrue; } }
publicclassSolution { publicboolCanFormArray(int[] arr, int[][] pieces) { int n = arr.Length, m = pieces.Length; Dictionary<int, int> index = new Dictionary<int, int>(); for (int i = 0; i < m; i++) { index.Add(pieces[i][0], i); } for (int i = 0; i < n;) { if (!index.ContainsKey(arr[i])) { returnfalse; } int j = index[arr[i]], len = pieces[j].Length; for (int k = 0; k < len; k++) { if (arr[i + k] != pieces[j][k]) { returnfalse; } } i = i + len; } returntrue; } }
boolcanFormArray(int* arr, int arrSize, int** pieces, int piecesSize, int* piecesColSize){ int n = arrSize, m = piecesSize; HashItem *index = NULL; for (int i = 0; i < m; i++) { hashAddItem(&index, pieces[i][0], i); } for (int i = 0; i < n;) { if (!hashFindItem(&index, arr[i])) { hashFree(&index); returnfalse; } int j = hashGetItem(&index, arr[i], 0); int len = piecesColSize[j]; for (int k = 0; k < len; k++) { if (arr[i + k] != pieces[j][k]) { hashFree(&index); returnfalse; } } i = i + len; } hashFree(&index); returntrue; }
var canFormArray = function(arr, pieces) { const n = arr.length, m = pieces.length; const index = newMap(); for (let i = 0; i < m; i++) { index.set(pieces[i][0], i); } for (let i = 0; i < n;) { if (!index.has(arr[i])) { returnfalse; } const j = index.get(arr[i]), len = pieces[j].length; for (let k = 0; k < len; k++) { if (arr[i + k] != pieces[j][k]) { returnfalse; } } i = i + len; } returntrue; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funccanFormArray(arr []int, pieces [][]int)bool { index := make(map[int]int, len(pieces)) for i, p := range pieces { index[p[0]] = i } for i := 0; i < len(arr); { j, ok := index[arr[i]] if !ok { returnfalse } for _, x := range pieces[j] { if arr[i] != x { returnfalse } i++ } } returntrue }