算法要求
You are given two arrays a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array. Find max(abs(length(x) − length(y))), If a1 or a2 are empty return -1 in each language except in Haskell where you will return Nothing.
总体思路就是先转换数组,再求极值。
方法一:
sort()排序
function mxdiflg(a1, a2) {
function arrSortByLen(a, b){
if(a.length<=b.length){
return -1;
}
if(a.length>b.length){
return 1;
}
}
if(a1.length==0||a2.length==0){
return -1;
}
a1 = a1.sort(arrSortByLen);
a2 = a2.sort(arrSortByLen);
var a1Len = a1.length,
a2Len = a2.length,
firstData = a2[a2Len-1].length-a1[0].length,
seconData = a1[a1Len-1].length-a2[0].length;
return Math.max(firstData, seconData);
}
方法二:
加入数组的map()方法
function mxdiflg(a1, a2) {
function sortByLen(ele, index){
return this[index] = ele.length;
}
if(a1.length ==0 || a2.length ==0){
return -1;
}else {
a1 = a1.map(sortByLen);
a2 = a2.map(sortByLen);
var a1Max = Math.max.apply(null, a1),
a1Min = Math.min.apply(null, a1),
a2Max = Math.max.apply(null, a2),
a2Min = Math.min.apply(null, a2);
return Math.max(Math.abs(a1Max-a2Min), Math.abs(a2Max-a1Min));
}
}