数组

2023-02-27 14:44:36

数组洗牌

shuffleArray.ts
          function shuffleArray<T>(array: T[]) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

        

数组去重

uniqueBy.ts
          function uniqueBy<T, K extends keyof T>(array: T[], getKey?: K | ((item: T) => T[K])) {
  const result: T[] = []
  const keys = new Set()

  array.forEach(item => {
    const key = getKey ? (typeof getKey === 'function' ? getKey(item) : item[getKey]) : item
    if (!keys.has(key)) {
      keys.add(key)
      result.push(item)
    }
  })

  return result
}

        

合并区间

  • 输入:一组区间([start, end]),例如 [[1, 3], [2, 6], [8, 10], [15, 18]]
  • 输出:合并重叠区间后的结果,例如 [[1, 6], [8, 10], [15, 18]]
mergeIntervals.ts
          function mergeIntervals(intervals: Array<[number, number]>): Array<[number, number]> {
  if (!intervals.length) return []

  // 首先将区间按起始位置排序
  intervals.sort((a, b) => a[0] - b[0])

  const merged = [intervals[0]!] // 初始化合并后的区间列表

  for (let i = 1; i < intervals.length; i++) {
    const current = intervals[i]!
    const lastMerged = merged.at(-1)!

    // 如果当前区间与最后一个合并的区间重叠,则合并它们
    if (current[0] <= lastMerged[1]) {
      lastMerged[1] = Math.max(lastMerged[1], current[1]) // 更新合并区间的结束位置
    } else {
      merged.push(current) // 如果不重叠,直接添加当前区间
    }
  }

  return merged
}

        
© 2021-2025 sunshj's Blog