0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでlower_bound(),upper_bound()

Posted at

AtCoder Beginner Contest 248
D - Range Count Query
自作の二分探索の結果を場合分けして解答したが
提出結果1

そもそもlower_boud()とupper_bound()があれば場合分けをする必要がないかつ
解答コードを少し改造すれば両方とも実装可能だったのでここに記す

lower_bound()
function lower_bound(target, arr) {
  let left = -1
  let right = arr.length + 1

  while (right - left > 1) {
    let mid = (right + left) / 2
    if ((right + left) % 2 !== 0) {
      mid = (right + left + 1) / 2
    }
    if (target === arr[mid]) {
      return mid
    }
    if (target > arr[mid]) {
      left = mid
    } else {
      right = mid
    }
  }
  return right
}
upper_bound()
function upper_bound(target, arr) {
  let left = -1
  let right = arr.length + 1

  while (right - left > 1) {
    let mid = (right + left) / 2
    if ((right + left) % 2 !== 0) {
      mid = (right + left + 1) / 2
    }
    if (target === arr[mid]) {
      return mid + 1
    }
    if (target > arr[mid]) {
      left = mid
    } else {
      right = mid
    }
  }
  return right
}

ソート済みの配列に対してtarget以上の数が初めて現れる場所はlower_bound()
ソート済みの配列に対してtargetより大きい数が初めて現れる場所はupper_bound()

使用した結果↓
提出結果2

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?