1460. Make two arrays equal by flipping sub-arrays (C++)
1 topic description
Give you two integer arrays of the same length target and arr.
In each step, you can select any non-empty sub-array of arr and flip it. You can perform this process any number of times.
If you can make arr become the same as target, return True; otherwise, return False.
2 Example description
2.1 Example 1
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Explanation: You can make arr become target according to the following steps:
1- Flip the sub-array [2,4 ,1], arr becomes [1,4,2,3]
2- flip sub-array [4,2], arr becomes [1,2,4,3]
3- flip sub-array [4,3], arr becomes [1,2,3,4] The
above method is not the only one, there are many ways to turn arr into a target.
2.2 Example 2
Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any flipping.
2.3 Example 3
Input: target = [1,12], arr = [12,1]
Output: true
2.4 Example 4
Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr does not have the number 9, so it cannot become target anyway.
2.5 Example 5
Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
Output: true
3 Problem solving tips
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
4 Problem-solving ideas
It is easy to understand by sorting and comparing them one by one.
5 Detailed source code (C++)
class Solution {
public:
bool canBeEqual(vector<int>& target, vector<int>& arr) {
int count = 0 ;
sort( target.begin() , target.end() );
sort( arr.begin() , arr.end() );
for ( int i = 0 ; i < target.size() ; i ++ )
{
if ( target[i] == arr[i] )
{
count ++ ;
}
}
if ( count == target.size() )
{
return true ;
}
else
{
return false;
}
}
};