Description
This problem was asked by Google.
Given a list of numbers and a number k
, return whether any two numbers from the list add up to k
.
For example, given [10, 15, 3, 7]
and k
of 17
, return true since 10 + 7
is 17
.
Bonus: Can you do this in one pass?
Kotlin Solution
參考 leet code 連接
https://leetcode.com/problems/two-sum/
假設題目如下
class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
// 填空
}
}
Kotlin 參考解答
點擊展開解答
class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
val map = hashMapOf<Int, Int>()
for (i in nums.indices) {
val temp = target - nums[i]
if (map.containsValue(nums[i])) {
val keys = map.filterValues { it == nums[i] }.keys
return intArrayOf(keys.first(), i)
}
map.put(i, temp)
}
throw IllegalArgumentException("No two sum solution")
}
}