1640. Check Array Formation Through Concatenation 能否连接形成数组
生活随笔
收集整理的這篇文章主要介紹了
1640. Check Array Formation Through Concatenation 能否连接形成数组
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給你一個(gè)整數(shù)數(shù)組 arr ,數(shù)組中的每個(gè)整數(shù) 互不相同 。另有一個(gè)由整數(shù)數(shù)組構(gòu)成的數(shù)組 pieces,其中的整數(shù)也 互不相同 。請(qǐng)你以 任意順序 連接 pieces 中的數(shù)組以形成 arr 。但是,不允許 對(duì)每個(gè)數(shù)組 pieces[i] 中的整數(shù)重新排序。
如果可以連接 pieces 中的數(shù)組形成 arr ,返回 true ;否則,返回 false 。
?
示例 1:
輸入:arr = [85], pieces = [[85]] 輸出:true示例 2:
輸入:arr = [15,88], pieces = [[88],[15]] 輸出:true 解釋:依次連接 [15] 和 [88]示例 3:
輸入:arr = [49,18,16], pieces = [[16,18,49]] 輸出:false 解釋:即便數(shù)字相符,也不能重新排列 pieces[0]示例 4:
輸入:arr = [91,4,64,78], pieces = [[78],[4,64],[91]] 輸出:true 解釋:依次連接 [91]、[4,64] 和 [78]示例 5:
輸入:arr = [1,3,5,7], pieces = [[2,4,6,8]] 輸出:false?
提示:
- 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 中的整數(shù) 互不相同
- pieces 中的整數(shù) 互不相同(也就是說,如果將 pieces 扁平化成一維數(shù)組,數(shù)組中的所有整數(shù)互不相同)
邏輯
這題直接分析就可以了,用兩個(gè)指針分別遍歷arr和piece的元素,如果找到了就往前走,沒找到就直接return False。
Python
class Solution:def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:arrIndex = 0while arrIndex < len(arr):for piece in pieces:if arr[arrIndex] == piece[0] and arr[arrIndex: arrIndex + len(piece)] == piece:arrIndex += len(piece)breakelse:return Falsereturn True總結(jié)
以上是生活随笔為你收集整理的1640. Check Array Formation Through Concatenation 能否连接形成数组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 941. Valid Mountain
- 下一篇: 1470. Shuffle the Ar