Skip to content

Commit d8a6069

Browse files
committed
two sum
1 parent 31732aa commit d8a6069

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

two-sum/iam-edwin.kt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
fun twoSum(nums: IntArray, target: Int): IntArray {
3+
val indexMap = nums.mapIndexed { index, num -> num to index }
4+
.groupBy({ it.first }, {it.second})
5+
6+
indexMap.forEach { (firstNum, firstIndicies) ->
7+
val secondNum = target - firstNum
8+
if (firstNum == secondNum) {
9+
if (firstIndicies.size > 1) {
10+
return intArrayOf(firstIndicies[0], firstIndicies[1])
11+
}
12+
} else {
13+
val secondIndicies = indexMap[secondNum]
14+
if (secondIndicies != null) {
15+
return intArrayOf(firstIndicies[0], secondIndicies[0])
16+
}
17+
}
18+
}
19+
20+
return intArrayOf()
21+
}
22+
}

0 commit comments

Comments
 (0)