File tree Expand file tree Collapse file tree 2 files changed +26
-0
lines changed
kotlin/Hash Maps and Sets Expand file tree Collapse file tree 2 files changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ fun pairSumUnsortedTwoPass (nums : List <Int >, target : Int ): List <Int > {
2
+ val numMap = mutableMapOf<Int , Int >()
3
+ // First pass: Populate the hash map with each number and its
4
+ // index.
5
+ for ((i, num) in nums.withIndex()) {
6
+ numMap[num] = i
7
+ }
8
+ // Second pass: Check for each number's complement in the hash map.
9
+ for ((i, num) in nums.withIndex()) {
10
+ val complement = target - num
11
+ if (complement in numMap && numMap[complement] != i) {
12
+ return listOf (i, numMap[complement]!! )
13
+ }
14
+ }
15
+ return emptyList()
16
+ }
Original file line number Diff line number Diff line change
1
+ fun pairSumUnsorted (nums : List <Int >, target : Int ): List <Int > {
2
+ val hashmap = mutableMapOf<Int , Int >()
3
+ for ((i, x) in nums.withIndex()) {
4
+ if (target - x in hashmap) {
5
+ return listOf (hashmap[target - x]!! , i)
6
+ }
7
+ hashmap[x] = i
8
+ }
9
+ return emptyList()
10
+ }
You can’t perform that action at this time.
0 commit comments