题目描述
给你两个长度相同的整数数组target和arr。每一步中,你可以选择arr的任意非空子数组并将它翻转。你可以执行此过程任意次。
如果你能让arr变得与target相同,返回True;否则,返回False。
示例1:
输入:target=[1,2,3,4],arr=[2,4,1,3]
输出:true
解释:你可以按照如下步骤使arr变成target:
1-翻转子数组[2,4,1],arr变成[1,4,2,3]
2-翻转子数组[4,2],arr变成[1,2,4,3]
3-翻转子数组[4,3],arr变成[1,2,3,4]
上述方法并不是唯一的,还存在多种将arr变成target的方法。
解题思路
1. 如果2个数组的元素是一致的,那么通过任意次数翻转后,一定能得到目标数组;
2. 判断2个数组的元素是否一致,可以使用哈希表,来解决问题。
代码实现如下:
import java.util.HashMap;
import java.util.Map;
class Solution1 {
public boolean canBeEqual(int[] target, int[] arr) {
if (target.length != arr.length) {
return false;
}
Map<Integer, Integer> mapTarget = new HashMap<>(target.length);
Map<Integer, Integer> mapArr = new HashMap<>(arr.length);
for (int c : target) {
int count = mapTarget.getOrDefault(c, 0);
mapTarget.put(c, ++count);
}
for (int c : arr) {
int count = mapArr.getOrDefault(c, 0);
mapArr.put(c, ++count);
}
for (Map.Entry<Integer, Integer> entry : mapArr.entrySet()) {
Integer count = mapTarget.get(entry.getKey());
if (count == null) {
return false;
}
if (entry.getValue() != count) {
return false;
}
}
return true;
}
}
代码优化
上面的代码在耗时上还比较高,考虑使用数组代替哈希表,根据题目意思:
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
那么只需要初始化的数组大小为1001就可以了,具体实现代码如下:
class Solution {
public boolean canBeEqual(int[] target, int[] arr) {
int[] mapTarget = new int[1001];
int[] mapArr = new int[1001];
for (int c : target) {
mapTarget[c]++;
}
for (int c : arr) {
mapArr[c]++;
}
for (int i = 0; i < mapArr.length; i++) {
if (mapArr[i] != mapTarget[i]) {
return false;
}
}
return true;
}
}
这两种代码实现耗时差别如下:
总结
这道题解题思路上复杂度不高,核心还是降低耗时;欢迎有更简单、高效的思路回复。