Created
October 28, 2021 12:16
-
-
Save carolinemusyoka/306b01c75ffa8c32a303fa1eb73ad394 to your computer and use it in GitHub Desktop.
1. Two Sum
This file contains hidden or 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
//Solves the problem in O(n) time complexity | |
class Solution { | |
fun twoSum(nums: IntArray, target: Int): IntArray { | |
//initialize an empty HashMap | |
val map = hashMapOf<Int, Int>() | |
//and for every element in the array, if it exists in the Map, | |
//check if its complement exists a in the Map or not. If the complement exists then return the indices | |
//of the current element and the complement. | |
//Otherwise, put the element in the Map, and move to the next iteration. | |
for(i in 0..nums.size - 1){ | |
if(map.containsKey(target - nums[i])){ | |
val tmp = map.get(target - nums[i])!!.toInt() | |
val ans : IntArray = intArrayOf(tmp,i) | |
return ans | |
} | |
map.put(nums[i],i) | |
} | |
return intArrayOf() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment