Last active
August 8, 2022 10:31
-
-
Save Husseinhj/de1dfff478752f87313bcc11e295fa17 to your computer and use it in GitHub Desktop.
Two Combination 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
package org.kotlinlang.play | |
//Playground: https://pl.kotl.in/5Cjs0Zde6 | |
fun main() { | |
val k = 10 | |
val sample = arrayOf(1,1,2,23,4,9,13,6,9) | |
val result = indexOfAddUp(sample, k) | |
println(result) | |
} | |
fun indexOfAddUp(sample: Array<Int>, k: Int): List<List<Int>> { | |
val result = mutableListOf<List<Int>>() | |
val hashIndex = hashMapOf<Int, MutableList<Int>>() | |
sample.forEachIndexed {index, number -> | |
if (hashIndex.containsKey(number)) { | |
val tempList = hashIndex[number] | |
tempList!!.add(index) | |
hashIndex[number] = tempList | |
} else { | |
hashIndex[number] = mutableListOf(index) | |
} | |
val diff = k - number | |
if (hashIndex.containsKey(diff)) { | |
val indexList = hashIndex[diff] | |
val firstIndex = indexList!!.first() | |
indexList.remove(firstIndex) | |
hashIndex[diff] = indexList | |
result.add(listOf(firstIndex, index)) | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In playground:
https://pl.kotl.in/5Cjs0Zde6