codewars算法题-求两数组元素长度差值极大值
来源:互联网 发布:linux ip设置 编辑:程序博客网 时间:2024/05/07 02:27
算法要求
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)); }}
0 0
- codewars算法题-求两数组元素长度差值极大值
- 求数组元素最大差值
- codewars算法题-求因子
- 交换两数组元素使两数组和差值最小
- codewars算法题(求因子)
- 求数组相邻元素差值的最大值快速算法(C++版)
- 算法--微软面试题:求一个整数数组元素间最小差值
- 笔试题---求两数组相同元素
- 无序数组求相邻元素最大差值(tiger基金的笔试题)
- 求任何两个数组元素的差值中的最大值
- 【面试】求数组元素最大差值的问题
- 【面试】求数组元素最大差值的问题
- 求一个数组中两个元素的最大差值
- 遗传算法求函数极大值
- 两算法:求数组元素出现次数和求子数组最大和
- 关于顺序数组求最大差值或最大收益算法
- 两数组求交集元素-C描述
- 求数组中出现次数大于数组长度一半元素
- web前端开发常见面试题
- gym101138J(树链剖分,线段树维护区间连续子段最大和,好题)
- 167. Two Sum II - Input array is sorted
- Uva 101 The Blocks Problem(不定长数组 vector)
- pat a1058
- codewars算法题-求两数组元素长度差值极大值
- 安全访问认证 MD5 个人
- cut用法详细解析 (2)
- php中文截取无乱码
- cocos2dx 优秀博客
- 小白日记_错误:org.hibernate.HibernateException: No CurrentSessionContext configured!
- 在Rails中使用Kindeditor富文本编辑器的那些坑...
- u3d canvas设置
- HOST文件在WINDOWS下是什么作用?