【发布时间】:2021-05-31 02:26:21
【问题描述】:
所以我在 codewar 上遇到了一个编码问题。指示去 “给定两个数组 a 和 b,编写一个函数 comp(a, b) (orcompSame(a, b)) 来检查两个数组是否具有“相同”元素,并具有相同的多重性。“相同”在这里意味着b 中的元素是平方中的元素,与顺序无关。
示例
有效数组
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121、14641、20736、361、25921、361、20736、361]
comp(a, b) 返回真,因为在 b 中,121 是 11 的平方,14641 是 121 的平方,20736 是 144 的平方,361 是 19 的平方,25921 是 161 的平方,以此类推。如果我们将 b 的元素写成正方形,那就很明显了:
a = [121, 144, 19, 161, 19, 144, 19, 11] b = [1111, 121121, 144144, 1919, 161161, 1919, 144144, 1919] 无效的数组 例如,如果我们将第一个数字更改为其他数字,comp 可能不再返回 true:
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [132、14641、20736、361、25921、361、20736、361]
comp(a,b) 返回 false,因为在 b 中 132 不是任意数量 a 的平方。
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121、14641、20736、36100、25921、361、20736、361]
comp(a,b) 返回 false,因为在 b 中 36100 不是任意数量 a 的平方。
备注 a 或 b 可能是 [](除 R、Shell 之外的所有语言)。 a 或 b 可能为 nil 或 null 或 None 或无(C++、Elixir、Haskell、PureScript、Pascal、R、Rust、Shell 除外)。 如果 a 或 b 为 nil(或 null 或 None),则问题没有意义,因此返回 false。”
这是我的解决方案
import java.util.HashMap;
公共类主{
public static int BiggestElement(int [] arr) {
int result = 0;
result = arr[0];
for(int i=0;i<arr.length;i++) {
if(arr[i]>= result) {
result = arr[i];
}
}
return result;
}
public static boolean comp(int[] a, int []b) {
int size = a.length;
if(a.length != b.length) {
System.out.println("They don't have the same size");
return false;
}
else {
//First we need to check which one has the biggest element
int biggestA = 0;
int biggestB = 0;
System.out.println(biggestA = BiggestElement(a));
System.out.println(biggestB = BiggestElement(b));
//creating two maps
HashMap<Integer, Integer> map1 = new HashMap<Integer,Integer>();
HashMap<Integer, Integer> map2 = new HashMap<Integer,Integer>();
//now we put every value of b inside the map
for(int i = 0; i<a.length;i++) {
map1.put(a[i], i);
map2.put(b[i], i);
}
//now we do the actual comparision
if(biggestA>biggestB) {
for(int i=0;i<size;i++) {
if(!map1.containsKey(b[i]*b[i])) {
return false;
}
}
} else {
for(int i=0;i<size;i++) {
if(!map2.containsKey(a[i]*a[i])) {
System.out.println("map 1 doesn't contain " + (b[i]*b[i]));
return false;
}
}
}
}
return true;
}
public static void main(String[] args) {
int[] a = new int[]{121, 144, 19, 161, 19, 144, 19, 11};
int[] b = new int[]{121, 14641, 20736, 361, 25921, 361, 20736, 361};
System.out.println(comp(a,b));
}
}
我提交了我的代码,他们进行了 13 次测试,但我失败了 3 次。任何人都向我提出任何建议或解决方案,以便我改进。
【问题讨论】:
-
你需要告诉我们更多关于失败的测试
-
您发布的说明有点乱码。也许你可以把它们写得更清楚(更简洁)。
-
code wards 的奇怪之处在于它没有显示我的测试失败的原因。如果有的话,我来这里是为了更好的解决方案
标签: java arrays data-structures hashmap