Problem
Two Pointers
class Solution {
fun twoSum(numbers: IntArray, target: Int): IntArray {
val result = IntArray(2) { 0 }
val size = numbers.size
var s = 0
var e = size - 1
while (s < e) {
if (numbers[s] + numbers[e] < target) s++
else if (numbers[s] + numbers[e] > target) e--
else {
result[0] = s + 1
result[1] = e + 1
break
}
}
return result
}
}
Binary Search
class Solution {
fun twoSum(numbers: IntArray, target: Int): IntArray {
val result = IntArray(2) { 0 }
val size = numbers.size
for (i in numbers.indices) {
val key = target - numbers[i]
var s = i + 1
var e = size - 1
while (s <= e) {
val mid = s + (e - s) / 2
if (numbers[mid] > key) e = mid - 1
else if (numbers[mid] < key) s = mid + 1
else {
result[0] = i + 1
result[1] = mid + 1
return result
}
}
}
return result
}
}