1. Two Sum
Problem
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].Analysis
Code
Last updated
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].Last updated
class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
for (i: Int in nums.indices) {
val k = target - nums[i]
for (j: Int in IntRange(i + 1, nums.lastIndex)) {
if (k == nums[j]) {
return intArrayOf(i, j)
}
}
}
throw IllegalArgumentException("No two sum solution")
}
}class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
val map = HashMap<Int, Int>()
nums.forEachIndexed { i, n ->
val index = map[target - n]
if (index != null) {
return intArrayOf(i, index)
}
map[n] = i
}
throw IllegalArgumentException("No two sum solution")
}
}