给定一个由N 个不同整数组成的数组arr[]和一个由不同整数组成的数组pieces[]的列表,任务是检查给定的数组列表是否可以以任何顺序连接以获得给定的数组。如果可能,则打印“是” 。否则,打印“否” 。
例子:
Input: arr[] = {1, 2, 4, 3}, pieces[][] = {{1}, {4, 3}, {2}}
Output: Yes
Explanation:
Rearrange the list to {{1}, {2}, {4, 3}}.
Now, concatenating the all the arrays from the list generates the sequence {1, 2, 4, 3} which is same as the given array.
Input: arr[] = {1, 2, 4, 3}, pieces = {{1}, {2}, {3, 4}}
Output: No
Explanation:
There is no possible permutation of given list such that after concatenating the generated sequence becomes equal to the given array.
朴素的方法:最简单的方法是遍历给定的数组arr[] ,对于每个元素arr[i] ,检查列表中是否存在任何数组,使其从arr[i]开始。如果发现为真则增量I而本数组中的元素发现等于给Arr [i]中。如果它们不相等,则打印No 。重复上述步骤直到i < N 。遍历给定数组的元素后,打印Yes 。
时间复杂度: O(N 2 )
辅助空间: O(N)
有效的方法:这个想法是通过使用 Map 数据结构存储给定数组arr[] 中存在的元素的索引来使用哈希的概念。请按照以下步骤解决问题:
- 创建 地图 存储给定数组arr[]元素的索引。
- 迭代列表中存在的每个数组,对于每个数组,请按照以下步骤操作:
- 从Map 中查找数组arr[] 中第一个元素的索引。
- 检查获取的数组是否是数组arr[]的子数组或不是从之前找到的索引开始。
- 如果子数组不等于找到的数组,则打印No 。
- 否则,在遍历给定数组后,打印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)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。