LeetCode 1640 Check Array Formation Through Concatenation (Python)

Posted by 小明MaxMing on January 3, 2020

题目

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.

解题思路

将所有pieces放到一个字典里,key是数组的第一个数,这样在遍历的时候就可以找到对应的piece,判断是否可以构成输入的数组

代码

class Solution:
    def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
        d = {x[0]: x for x in pieces}
        return list(chain(*[d.get(num, []) for num in arr])) == arr

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅