Created
April 18, 2022 02:02
-
-
Save Turskyi/0ac601c74cae5ed792907dd8604e6726 to your computer and use it in GitHub Desktop.
Return two unique indices (one based) such that the values at those indices sums to the given target.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given an array of integers nums and an integer target, | |
return indices of the two numbers such that they add up to target. | |
Example: | |
Input: nums = [2,7,11,15], target = 9 | |
Output: [0,1] | |
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. | |
* */ | |
fun twoSum(nums: IntArray, target: Int): IntArray { | |
val map: MutableMap<Int, Int> = mutableMapOf() | |
for (i: Int in nums.indices) { | |
if (map.containsKey(target - nums[i])) { | |
return intArrayOf(map.get(target - nums[i])!!, i) | |
} else { | |
map.put(nums[i], i) | |
} | |
} | |
return intArrayOf(0, 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment