code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

167 Two Sum 2

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const twoSum2 = (numbers, target) => {
  let left = 0
  let right = numbers.length - 1
  while (left < right) {
    if (numbers[left] + numbers[right] == target) {
      return [left + 1, right + 1]
    }
    if (numbers[left] + numbers[right] > target) {
      right -= 1
    } else {
      left += 1
    }
  }
}

console.log(twoSum2([2, 7, 11, 15], 9))

Created 2022-03-18T15:41:00+00:00, updated 2022-03-19T10:16:15+00:00 · History · Edit