Two sum in kotlin

Viewed 48

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

I am adding piece of code.

fun main() {
//    val nums = intArrayOf(2, 7, 11, 15)
//    val target = 9
    val nums = intArrayOf(3, 2, 4)
    val target = 6
//    val nums = intArrayOf(3, 3)
//    val target = 6
    twoSum(nums, target).forEach {
        print(" $it")
    }
}

fun twoSum(nums: IntArray, target: Int): IntArray {
    val map = mutableMapOf<Int, Int>()
    nums.forEachIndexed { index, i ->
        map[i]?.let {
            return intArrayOf(it, index)
        }
        map[target - i] = index
    }
    return intArrayOf()
}

My youtube link is described that I am debugging the code. My question is how

map[i]?.let {
                return intArrayOf(it, index)
            }

is going inside the 1st and 2nd iteration of return statment and it not going in 3rd iteration. Can anyone help me on this. Thanks

0 Answers
Related