1. 程式人生 > 其它 >leetcode 1640. Check Array Formation Through Concatenation(python)

leetcode 1640. Check Array Formation Through Concatenation(python)

技術標籤:leetcodeleetcode

描述

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.

Example 1:

Input: arr = [85], pieces = [[85]]
Output: true

Example 2:

Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] then [88]

Example 3:

Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
Explanation: Even though the numbers match, we cannot reorder pieces[0].

Example 4:

Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
Explanation: Concatenate [91] then [4,64] then [78]

Example 5:

Input: arr = [1,3,5,7], pieces = [[2,4,6,8]]
Output: false

Note:

  • 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
  • The integers in arr are distinct.
  • The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).

解析

根據題意,就是把 pieces 中的元素按照任意順序拼接起來能夠和 arr 一樣,那就返回 true ,否則返回 false 。實現起來使用字典型別 d 來儲存 pieces 中的每個子列表及其第一個元素,然後遍歷 arr 元素用其來獲取 d 中的元素,然後將結果拼接起來判斷是否相等即可。

解答

class Solution(object):
    def canFormArray(self, arr, pieces):
        """
        :type arr: List[int]
        :type pieces: List[List[int]]
        :rtype: bool
        """
        res = []
        d = {x[0]:x for x in pieces}
        for x in arr:
            res += d.get(x, [])
        return res==arr

執行結果

Runtime: 40 ms, faster than 15.53% of Python online submissions for Check Array Formation Through Concatenation.
Memory Usage: 13.3 MB, less than 95.24% of Python online submissions for Check Array Formation Through Concatenation.

原題連結:https://leetcode.com/problems/check-array-formation-through-concatenation/