Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created April 18, 2022 02:02
Show Gist options
  • Save Turskyi/0ac601c74cae5ed792907dd8604e6726 to your computer and use it in GitHub Desktop.
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.
/*
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