題目鏈接:https://leetcode.cn/problems/form-array-by-concatenating-subarrays-of-another-array/
題目描述:
給你一個長度為 n
的二維整數(shù)數(shù)組 groups
,同時給你一個整數(shù)數(shù)組 nums
。
你是否可以從 nums
中選出 n
個 不相交 的子數(shù)組,使得第 i
個子數(shù)組與 groups[i]
(下標(biāo)從 0 開始)完全相同,且如果 i > 0
,那么第 (i-1)
個子數(shù)組在 nums
中出現(xiàn)的位置在第 i
個子數(shù)組前面。(也就是說,這些子數(shù)組在 nums
中出現(xiàn)的順序需要與 groups
順序相同)
如果你可以找出這樣的 n
個子數(shù)組,請你返回 true
,否則返回 false
。
如果不存在下標(biāo)為 k
的元素 nums[k]
屬于不止一個子數(shù)組,就稱這些子數(shù)組是 不相交 的。子數(shù)組指的是原數(shù)組中連續(xù)元素組成的一個序列。
示例 1:
輸入:groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
輸出:true
解釋:你可以分別在 nums 中選出第 0 個子數(shù)組 [1,-1,0,1,-1,-1,3,-2,0] 和第 1 個子數(shù)組 [1,-1,0,1,-1,-1,3,-2,0] 。
這兩個子數(shù)組是不相交的,因?yàn)樗鼈儧]有任何共同的元素。
示例 2:
輸入:groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]
輸出:false
解釋:選擇子數(shù)組 [1,2,3,4,10,-2] 和 [1,2,3,4,10,-2] 是不正確的,因?yàn)樗鼈兂霈F(xiàn)的順序與 groups 中順序不同。
[10,-2] 必須出現(xiàn)在 [1,2,3,4] 之前。
示例 3:
輸入:groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]
輸出:false
解釋:選擇子數(shù)組 [7,7,1,2,3,4,7,7] 和 [7,7,1,2,3,4,7,7] 是不正確的,因?yàn)樗鼈儾皇遣幌嘟蛔訑?shù)組。
它們有一個共同的元素 nums[4] (下標(biāo)從 0 開始)。
提示:
groups.length == n
1 <= n <= 103
1 <= groups[i].length, sum(groups[i].length) <= 103
1 <= nums.length <= 103
-107 <= groups[i][j], nums[k] <= 107
解法:暴力法
直接遍歷groups
數(shù)組中的每一個數(shù)組元素groups[i]
,使用index來標(biāo)識當(dāng)前遍歷nums的下標(biāo),在遍歷對照groups
數(shù)組之前,都先用temp來把當(dāng)前滿足groups[i-1]的最小下標(biāo)index緩存起來。每一個在nums
查找有沒有連續(xù)的一段子數(shù)組與groups[i]
是相同的,若中間有一個元素不滿足,則讓index = temp + 1,繼續(xù)從頭遍歷groups[i]
,若遍歷完nums也沒有完全匹配groups,則返回false,否則返回true。
代碼:
class Solution {
public boolean canChoose(int[][] groups, int[] nums) {
int index = 0;
for (int i = 0; i < groups.length; i++) {
int temp = index;
for (int j = 0; j < groups[i].length; j++) {
if (index >= nums.length) {
return false;
}
if(groups[i][j] != nums[index]) {
index = temp + 1;
temp = index;
j = -1;
if (index >= nums.length) {
return false;
}
continue;
}
index++;
}
}
return true;
}
}