codewars算法题-求两数组元素长度差值极大值

算法要求

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));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值