📌  相关文章
📜  检查给定数组列表的任何排列的串联是否生成给定数组

📅  最后修改于: 2021-09-07 05:29:52             🧑  作者: Mango

给定一个由N 个不同整数组成的数组arr[]和一个由不同整数组成的数组pieces[]的列表,任务是检查给定的数组列表是否可以以任何顺序连接以获得给定的数组。如果可能,则打印“是” 。否则,打印“否”

例子:

朴素的方法:最简单的方法是遍历给定的数组arr[] ,对于每个元素arr[i] ,检查列表中是否存在任何数组,使其从arr[i]开始。如果发现为真则增量I而本数组中的元素发现等于给Arr [i]中。如果它们不相等,则打印No 。重复上述步骤直到i < N 。遍历给定数组的元素后,打印Yes

时间复杂度: O(N 2 )
辅助空间: O(N)

有效的方法:这个想法是通过使用 Map 数据结构存储给定数组arr[] 中存在的元素的索引来使用哈希的概念。请按照以下步骤解决问题:

  1. 创造 地图 存储给定数组arr[]元素的索引。
  2. 迭代列表中存在的每个数组,对于每个数组,请按照以下步骤操作:
    • Map 中查找数组arr[] 中第一个元素的索引。
    • 检查获取的数组是否是数组arr[]的子数组或不是从之前找到的索引开始。
  3. 如果子数组不等于找到的数组,则打印No
  4. 否则,在遍历给定数组后,打印Yes

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if it is possible
// to obtain array by concatenating
// the arrays in list pieces[]
bool check(vector& arr,
    vector>& pieces)
{
     
    // Stores the index of element in
    // the given array arr[]
    unordered_map m;
 
    for(int i = 0; i < arr.size(); i++)
        m[arr[i]] = i + 1;
 
    // Traverse over the list pieces
    for(int i = 0; i < pieces.size(); i++)
    {
         
        // If item size is 1 and
        // exists in map
        if (pieces[i].size() == 1 &&
          m[pieces[i][0]] != 0)
        {
            continue;
        }
 
        // If item contains > 1 element
        // then check order of element
        else if (pieces[i].size() > 1 &&
               m[pieces[i][0]] != 0)
        {
            int idx = m[pieces[i][0]] - 1;
 
            idx++;
 
            // If end of the array
            if (idx >= arr.size())
                return false;
 
            // Check the order of elements
            for(int j = 1; j < pieces[i].size(); j++)
            {
                 
                // If order is same as
                // the array elements
                if (arr[idx] == pieces[i][j])
                {
                     
                    // Increment idx
                    idx++;
 
                    // If order breaks
                    if (idx >= arr.size() &&
                     j < pieces[i].size() - 1)
                        return false;
                }
 
                // Otherwise
                else
                {
                    return false;
                }
            }
        }
 
        // Return false if the first
        // element doesn't exist in m
        else
        {
            return false;
        }
    }
 
    // Return true
    return true;
}
 
// Driver Code
int main()
{
     
    // Given target list
    vector arr = { 1, 2, 4, 3 };
 
    // Given array of list
    vector > pieces{ { 1 }, { 4, 3 }, { 2 } };
 
    // Function call
    if (check(arr, pieces))
    {
        cout << "Yes";
    }
    else
    {
        cout << "No";
    }
    return 0;
}
 
// This code is contributed by akhilsaini


Java
// Java program for the above approach
 
import java.util.*;
 
class GFG {
 
    // Function to check if it is possible
    // to obtain array by concatenating
    // the arrays in list pieces[]
    static boolean check(
        List arr,
        ArrayList > pieces)
    {
        // Stores the index of element in
        // the given array arr[]
        Map m
            = new HashMap<>();
 
        for (int i = 0; i < arr.size(); i++)
            m.put(arr.get(i), i);
 
        // Traverse over the list pieces
        for (int i = 0;
             i < pieces.size(); i++) {
 
            // If item size is 1 and
            // exists in map
            if (pieces.get(i).size() == 1
                && m.containsKey(
                       pieces.get(i).get(0))) {
                continue;
            }
 
            // If item contains > 1 element
            // then check order of element
            else if (pieces.get(i).size() > 1
                     && m.containsKey(
                            pieces.get(i).get(0))) {
 
                int idx = m.get(
                    pieces.get(i).get(0));
 
                idx++;
 
                // If end of the array
                if (idx >= arr.size())
                    return false;
 
                // Check the order of elements
                for (int j = 1;
                     j < pieces.get(i).size();
                     j++) {
 
                    // If order is same as
                    // the array elements
                    if (arr.get(idx).equals(
                            pieces.get(i).get(j))) {
 
                        // Increment idx
                        idx++;
 
                        // If order breaks
                        if (idx >= arr.size()
                            && j < pieces.get(i).size() - 1)
                            return false;
                    }
 
                    // Otherwise
                    else {
                        return false;
                    }
                }
            }
 
            // Return false if the first
            // element doesn't exist in m
            else {
                return false;
            }
        }
 
        // Return true
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given target list
        List arr
            = Arrays.asList(1, 2, 4, 3);
 
        ArrayList > pieces
            = new ArrayList<>();
 
        // Given array of list
        pieces.add(Arrays.asList(1));
        pieces.add(Arrays.asList(4, 3));
        pieces.add(Arrays.asList(2));
 
        // Function Call
        if (check(arr, pieces)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}


Python3
# Python3 program for the above approach
from array import *
 
# Function to check if it is possible
# to obtain array by concatenating
# the arrays in list pieces[]
def check(arr, pieces):
     
    # Stores the index of element in
    # the given array arr[]
    m = {}
     
    for i in range(0, len(arr)):
        m[arr[i]] = i + 1
     
    # Traverse over the list pieces
    for i in range(0, len(pieces)):
         
        # If item size is 1 and
        # exists in map
        if (len(pieces[i]) == 1 and
              m[pieces[i][0]] != 0):
            continue
     
        # If item contains > 1 element
        # then check order of element
        elif (len(pieces[i]) > 1 and
                m[pieces[i][0]] != 0):
            idx = m[pieces[i][0]] - 1
            idx = idx+1
             
            # If end of the array
            if idx >= len(arr):
                return False
             
            # Check the order of elements
            for j in range(1, len(pieces[i])):
                 
                # If order is same as
                # the array elements
                if arr[idx] == pieces[i][j]:
                    # Increment idx
                    idx = idx+1
                     
                    # If order breaks
                    if (idx >= len(arr) and
                           j < len(pieces[i]) - 1):
                        return False
                 
                # Otherwise
                else:
                    return False
         
        # Return false if the first
        # element doesn't exist in m
        else:
            return False
     
    # Return true
    return True
 
# Driver Code
if __name__ == "__main__":
     
    arr = [ 1, 2, 4, 3 ]
     
    # Given array of list
    pieces = [ [ 1 ], [ 4, 3 ], [ 2 ] ]
     
    # Function call
    if check(arr, pieces) == True:
        print("Yes")
    else:
        print("No")
 
# This code is contributed by akhilsaini


C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
class GFG{
 
// Function to check if it is possible
// to obtain array by concatenating
// the arrays in list pieces[]
static bool check(List arr,
                  List> pieces)
{
     
    // Stores the index of element in
    // the given array arr[]
    Dictionary m = new Dictionary();
 
    for(int i = 0; i < arr.Count; i++)
        m.Add(arr[i], i);
 
    // Traverse over the list pieces
    for(int i = 0; i < pieces.Count; i++)
    {
         
        // If item size is 1 and
        // exists in map
        if (pieces[i].Count == 1 &&
            m.ContainsKey(pieces[i][0]))
        {
            continue;
        }
 
        // If item contains > 1 element
        // then check order of element
        else if (pieces[i].Count > 1 &&
                 m.ContainsKey(pieces[i][0]))
        {
            int idx = m[pieces[i][0]];
 
            idx++;
 
            // If end of the array
            if (idx >= arr.Count)
                return false;
 
            // Check the order of elements
            for(int j = 1; j < pieces[i].Count; j++)
            {
                 
                // If order is same as
                // the array elements
                if (arr[idx] == pieces[i][j])
                {
                     
                    // Increment idx
                    idx++;
 
                    // If order breaks
                    if (idx >= arr.Count &&
                     j < pieces[i].Count - 1)
                        return false;
                }
 
                // Otherwise
                else
                {
                    return false;
                }
            }
        }
         
        // Return false if the first
        // element doesn't exist in m
        else
        {
            return false;
        }
    }
     
    // Return true
    return true;
}
 
// Driver Code
static public void Main()
{
     
    // Given target list
    List arr = new List(){ 1, 2, 4, 3 };
 
    List > pieces = new List >();
 
    // Given array of list
    pieces.Add(new List(){ 1 });
    pieces.Add(new List(){ 4, 3 });
    pieces.Add(new List(){ 2 });
 
    // Function call
    if (check(arr, pieces))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by akhilsaini


Javascript


输出:
Yes

时间复杂度: O(N*log N),其中 N 是给定数组的长度。
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live