Two Sum
Given an array of integers, return whether or not two numbers sum to a given target k
.
Note: you may not sum a number with itself.
Ex: Given the following...
[1, 3, 8, 2], k = 10, return true (8 + 2)
[3, 9, 13, 7], k = 8, return false
[4, 2, 6, 5, 2], k = 4, return true (2 + 2)
fun twoSum(nums: IntArray, target: Int): Boolean {
val map = HashMap<Int, Int>()
nums.forEachIndexed { index, item ->
val found = map[target - item]
found?.let {
return true
}
map[item] = index
}
return false
}
Steps
- Create a new HashMap
- Iterate over the array
- Subtract current array element from target
- Check if the above difference exists in HashMap
- If YES, then return true
- If NO, then store the current element as HashMap key and current index as its value
- Return false if nums array iteration is completed in the above step