Skip to content

杂项记录

冒泡算法

js
const arr = [9, 1, 3, 4, 5, 9, 0, 11]
/**
 *
 * @param {number[]} arr
 */
function bubbleSort(arr) {
  for (let idx = 0; idx < arr.length - 1; idx++) {
    let flag = true
    for (let j = 0; j < arr.length - 1 - idx; j++) {
      const j1 = arr[j]
      const j2 = arr[j + 1]

      if (j1 > j2) {
        [arr[j + 1], arr[j]] = [j1, j2]
        flag = false
      }
    }

    if (flag)
      break
  }
  return arr
}
const arr = [9, 1, 3, 4, 5, 9, 0, 11]
/**
 *
 * @param {number[]} arr
 */
function bubbleSort(arr) {
  for (let idx = 0; idx < arr.length - 1; idx++) {
    let flag = true
    for (let j = 0; j < arr.length - 1 - idx; j++) {
      const j1 = arr[j]
      const j2 = arr[j + 1]

      if (j1 > j2) {
        [arr[j + 1], arr[j]] = [j1, j2]
        flag = false
      }
    }

    if (flag)
      break
  }
  return arr
}

两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

ts
twoSum([1, 2, 3, 4, 5, 7], 9) // 索引[3,5]

/**
 *
 * @param {number[]} numbers
 * @param {number} target
 */
function twoSum(numbers, target) {
  const max = numbers.length
  let start = 0
  let end = max - 1

  while (start < end) {
    const sum = numbers[start] + numbers[end]

    if (sum === target)
      return [start, end]

    if (sum < target) {
      start++
      continue
    }

    if (sum > target) {
      end--
      continue
    }
  }
}
twoSum([1, 2, 3, 4, 5, 7], 9) // 索引[3,5]

/**
 *
 * @param {number[]} numbers
 * @param {number} target
 */
function twoSum(numbers, target) {
  const max = numbers.length
  let start = 0
  let end = max - 1

  while (start < end) {
    const sum = numbers[start] + numbers[end]

    if (sum === target)
      return [start, end]

    if (sum < target) {
      start++
      continue
    }

    if (sum > target) {
      end--
      continue
    }
  }
}