1.題目描述
給你一個整數數組 arr ,數組中的每個整數 互不相同 。另有一個由整數數組構成的數組 pieces,其中的整數也 互不相同 。請你以 任意順序 連接 pieces 中的數組以形成 arr 。但是,不允許 對每個數組 pieces[i] 中的整數重新排序。
如果可以連接 pieces 中的數組形成 arr ,返回 true ;否則,返回 false 。
示例 1:
輸入:arr = [15,88], pieces = [[88],[15]]
輸出:true
解釋:依次連接 [15] 和 [88]
示例 2:
輸入:arr = [49,18,16], pieces = [[16,18,49]]
輸出:false
解釋:即便數字相符,也不能重新排列 pieces[0]
示例 3:
輸入:arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
輸出:true
解釋:依次連接 [91]、[4,64] 和 [78]
2.解題思路與代碼
2.1 解題思路
這道題使用哈希表存放 pieces 中每個數字的第一個數字,value 便是該行數組在 pieces 中的索引。然后我們使用 index 指向 arr 數組開始遍歷,首先根據 arr 數組的 index 位置上的數字從哈希表中查看是否有該數字的 key ,如果不存在直接返回 false。如果存在則從哈希表中獲取出該數組在 pieces 中的索引并將數組提取出來,然后從 index 開始依次與該數組比較,如果存在不同的數字返回 false,匹配相同就重復上面步驟。以 arr = [91,4,64,78], pieces = [[78],[4,64],[91]] 為例,首先我們需要根據 pieces 得到哈希表 map:
然后我們使用 index 從 arr 數組的 0 位置開始,此時 index 指向 91,從 map 中可以看到存在 91 的 key,并且在 pieces 中數組為 [91],數字相同繼續遍歷
index 來到 arr 中的數字 4,map 中同樣存在數字 4 并且在 pieces 中數組為 [4,64],依次比較 index=1 是否等于4、index=2 時是否等于 64,比較后相同,繼續遍歷
此時 index 來到 3 位置數字為 78,map 同樣存在 78 并且數組中的值也是 78,遍歷完成,返回 true
2.2 代碼
class Solution {
public boolean canFormArray(int[] arr, int[][] pieces) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < pieces.length; i++) {
map.put(pieces[i][0], i);
}
int index = 0;
while (index < arr.length) {
if (!map.containsKey(arr[index])) {
return false;
}
int i = map.get(arr[index]);
for (int j = 0; j < pieces[i].length; j++) {
if (arr[index] != pieces[i][j]) {
return false;
}
index++;
}
}
return true;
}
}
2.3 測試結果
通過測試
3.總結
- 使用哈希表存放 pieces 中的數組第一位和索引
- 根據 arr 遍歷時第一位從 map 中取出 pieces 的數組依次比較