Given two integer arrays of equal length
In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.
Return True if you can make
target
and arr
.In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.
Return True if you can make
arr
equal to target
, or False otherwise.Example 1:
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Approach
Java
import java.util.Arrays;public class MakeTwoArrays {public static void main(String[] args) {int[] target = { 1, 2, 3, 4 }, arr = { 2, 4, 1, 3 };System.out.println(canBeEqual(target, arr));}static boolean canBeEqual(int[] target, int[] arr) {int n = target.length, m = arr.length;// if length of both array is different// then return falseif (n != m)return false;// sort both the arraysArrays.sort(target);Arrays.sort(arr);for (int i = 0; i < n; i++) {// if current value of both array is not same then// return falseif (target[i] != arr[i]) {return false;}}return true;}}
C++
#include <bits/stdc++.h>using namespace std;bool canBeEqual(vector<int> &target, vector<int> &arr){int n = target.size(), m = arr.size();//if length of both array is different//then return falseif (n != m)return false;//sort both the arrayssort(target.begin(), target.end());sort(arr.begin(), arr.end());for (int i = 0; i < n; i++){//if current value of both array is not same then//return falseif (target[i] != arr[i]){return false;}}return true;}int main(){vector<int> target = {1, 2, 3, 4}, arr = {2, 4, 1, 3};if (canBeEqual(target, arr))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment