题目描述
给你一个整数数组 arr ,数组中的每个整数 互不相同 。另有一个由整数数组构成的数组 pieces,其中的整数也 互不相同 。请你以 任意顺序 连接 pieces 中的数组以形成 arr 。但是,不允许 对每个数组 pieces[i] 中的整数重新排序。
如果可以连接 pieces 中的数组形成 arr ,返回 true ;否则,返回 false 。
样例
Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] then [88]
Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
Explanation: Concatenate [91] then [4,64] then [78]
限制
1 <= pieces.length <= arr.length <= 100
sum(pieces[i].length) == arr.length
1 <= pieces[i].length <= arr.length
1 <= arr[i], pieces[i][j] <= 100
arr 中的整数 互不相同
pieces 中的整数 互不相同(也就是说,如果将 pieces 扁平化成一维数组,数组中的所有整数互不相同)
算法1
(哈希表记录下标) $O(n)$
- 统计pieces中每个数组第一个元素的下标
- 遍历arr中每一个元素,查找是否在Map出现过, 没有则false
2.1 有则从当前这个元素开始移动, 依次比较是否和子数组中的元素相同,不同则return false
时间复杂度
$O(n)$ 最坏情况下,遍历完所有元素
空间复杂度
$O(n)$
C++ 代码
class Solution {
public:
bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) {
int n = arr.size(), m = pieces.size();
unordered_map<int, int> idx;
// count the index of each first num in the pieces array
for (int i = 0; i < m; i++) idx[pieces[i][0]] = i;
for (int i = 0; i < n;) {
int cur = arr[i];
// cur doesn't exist in the peices
if (idx.count(cur) == 0) return false;
auto nums = pieces[idx[cur]]; // the sub array of pieces
// compare each num in the sub array
for (int j = 0; j < nums.size(); j++, i++)
if (arr[i] != nums[j]) return false;
}
return true;
}
};