有序数组查找/去重 在保证数组有序的情况

时间:2022-9-17    作者:悬浮的青春    分类:


有序数组查找/去重 在保证数组有序的情况下,查找和去重可以采用二分法,降低复杂度。Lodash 也提供了一些针对有序(升序)数组的操作。 sortedIndex / sortedLastIndex 可以操作基本的 number 数组和 string 数组: // 返回插入该元素后仍然能保持数组有序的第一个下标位置 .sortedIndex(array, value); // 类似 sortedIndex,但返回最后一个能保持顺序的下标位置 .sortedLastIndex(array, value); // example .sortedIndex([1, 20, 20, 100, 500], 20); // 1 .sortedLastIndex([1, 20, 20, 100, 500], 20); // 3 复制代码 上面两个函数都只能在数字和字符串数组中使用,对于对象数组,可以用一个函数表示元素之间的排序依据: // 以 iteratee 转化后的结果排序 .sortedIndexBy(array, value [, iteratee]) .sortedLastIndexBy(array, value [, iteratee]) // example .sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, function(o) { return o.x; }); // => 0 复制代码 注意,sortedIndex/sortedLastIndex 并不能直接用于元素查找,比如上面返回下标 3,但 array[3] 是 100 而不是 20。 有序数组查找用 sortedIndexOf/sortedLastIndexOf,它的功能与 indexOf/lastIndexOf 一样,不过采用了二分查找。 .sortedIndexOf(array, value); .sortedLastIndexOf(array, value); // example .sortedIndexOf([4, 5, 5, 5, 6], 5); //1 复制代码 sortedUniq/sortedUniqBy 可以对有序数组去重。 .sortedUniq(array) .sortedUniqBy(array [, iteratee]) // example _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); // => [1.1, 2.3]

WRITTEN BY

avatar