LeetCode: Check Array Formation Through Concatenation
2020-12-11
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible to form the array arr from pieces. Otherwise, return false.
Note all the integers in arr and pieces are distinct, so we use a ordered_map to store the relationships between first element and index. Then iterate all elements in arr to check whether each element is same with arrays in pieces.
Time complexity: O(N), where N is the size of arr.
classSolution{ publicbooleancanFormArray(int[] arr, int[][] pieces){ Map<Integer, int[]> map = new HashMap<>(); for (int[] piece : pieces) { map.put(piece[0], piece); }
//iterate all the elements in arr for (int i = 0; i < arr.length; ) { int curVal = arr[i]; if (map.containsKey(curVal)) { int[] piece = map.get(curVal); for (int value : piece) { if (arr[i] == value) { i++; } else { returnfalse; } } } else { returnfalse; } } returntrue; } }