今天下午被一道算法题困了好久,终于看懂了。
参考了某个网友的解法,对于这个题进行一个梳理和总结
题目
js解法代码
整体思路
首先定义两个数组,arr1,arr2,
遍历logs数组来判断每段日志的最后一个值是不是数字,把字符串日志都放到arr1,数字日志都放到arr2
然后对arr1进行排序,
首先使用sort方法,让arr1按照标识符先排序,
然后根据日志中字母顺序排序,就是通过判断字母日志的Unicode的大小来排序。
最后再把数字追加到字母排序的后面
代码解析
arr1.sort((x,y) =>{
return x.slice(x.indexOf(' ')) < y.slice(y.indexOf(' ')) ? -1:1
})
这里比较难理解的一段代码主要涉及了
Array.prototype.slice()
String.prototype.indexOf()
Array.prototype.sort()
这几个js的函数。
Array.prototype.sort()
1.对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的
2.arr.sort([compareFunction]) compareFunction 用来指定按某种顺序进行排列的函数
sort里面进行函数自定义排序,例如
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
也可以写成:
var numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
// [1, 2, 3, 4, 5]
String.prototype.indexOf()
indexOf() 方法返回调用它的 String 对象中第一次出现的指定值的索引,从 fromIndex 处进行搜索。如果未找到该值,则返回 -1。
str.indexOf(searchValue [, fromIndex])。
searchValue是要被查找的字符串值。fromIndex是数字表示开始查找的位置。可以是任意整数,默认值为 0。
比如x=[‘g1 act car’] m我们要执行x.indexOf(’ '),就是需要寻找这个数组中第一个为空格的字符的索引值 ,为2.
另外:
若被查找的字符串 searchValue 是一个空字符串,将会产生“奇怪”的结果。如果 fromIndex 值为空,或者 fromIndex 值小于被查找的字符串的长度,返回值和以下的 fromIndex 值一样。
'hello world'.indexOf('') // 返回 0
'hello world'.indexOf('', 0) // 返回 0
'hello world'.indexOf('', 3) // 返回 3
'hello world'.indexOf('', 8) // 返回 8
如果 fromIndex 值大于等于字符串的长度,将会直接返回字符串的长度(str.length):
'hello world'.indexOf('', 11) // 返回 11
'hello world'.indexOf('', 13) // 返回 11
'hello world'.indexOf('', 22) // 返回 11
Array.prototype.slice()
slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。
例如:
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
所以综合这三种函数的学习,就可以发现这个排序算法的规律。
加入我们要对现在arr1排序
首先根据indexOf(“ ”),对于arr1[0]和arr1[1]我们发现对应的x.indexOf(’ ‘)=2,y.indexOf(’ ')=3
然后根据x.slice(x.indexOf(’ ‘)),y.slice(y.indexOf(’ '))就相当于x.slice(2),y.slice(3)。
x.slice(2)=[ act zoo ]
y.slice(3)=[ off key dog ]
最后排序
判断当x.slice(2)=[ act zoo ]<y.slice(3)=[ off key dog ]?-1:1
因为a<o,所以[ act zoo ] 排在[ off key dog ]前面。
剩下的以此类推,就会得到最终的结果。