You are given an array of distinct integers arr and an array of integer arrays
Return
pieces
, where the integers in 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 = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15]
then [88]
Approach
Java
public class ArrayFormationThroughConcatenation {public static void main(String[] args) {int[] arr = { 15, 88 };int[][] pieces = { { 88 }, { 15 } };System.out.println(canFormArray(arr, pieces));}static boolean canFormArray(int[] arr, int[][] pieces) {for (int i = 0; i < arr.length;) {int k = -1;for (int j = 0; j < pieces.length; j++) {if (pieces[j][0] == arr[i]) {k = j;break;}}if (k == -1)return false;else {int flag = 0;for (int l = 0; l < pieces[k].length; l++) {if (pieces[k][l] == arr[i])i++;else {flag = 1;break;}}if (flag == 1)return false;}}return true;}}
C++
#include <bits/stdc++.h>using namespace std;bool canFormArray(vector<int> &arr, vector<vector<int>> &pieces){for (int i = 0; i < arr.size();){int k = -1;for (int j = 0; j < pieces.size(); j++){if (pieces[j][0] == arr[i]){k = j;break;}}if (k == -1)return false;else{int flag = 0;for (int l = 0; l < pieces[k].size(); l++){if (pieces[k][l] == arr[i])i++;else{flag = 1;break;}}if (flag == 1)return false;}}return true;}int main(){vector<int> arr = {15, 88};vector<vector<int>> pieces = {{88}, {15}};if (canFormArray(arr, pieces))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment