https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Sudhir Singh Khanger

03/08/2021, 4:12 AM
Copy code
package leetcode

import kotlin.collections.set

fun main() {
    val nums1 = intArrayOf(1, 2, 2, 1)
    val nums2 = intArrayOf(2, 2)
    println(intersect(nums1, nums2).joinToString())
}

fun intersect(nums1: IntArray, nums2: IntArray): MutableList<Int> {
    val outputMap = hashMapOf<Int, Int>()
    val outputList = mutableListOf<Int>()

    for (i in nums1.indices) {
        if (nums1[i] in outputMap) {
            outputMap[nums1[i]]++
        } else {
            outputMap[nums1[i]] = 1
        }
    }

    for (i in nums2.indices) {
        if (nums2[i] in outputMap && outputMap[nums2[i]] > 1) {
            outputList.add(nums2[i])
            outputMap[nums1[i]]--
        }
    }

    return outputList
}
outputMap[nums1[i]]++
is complaining that
No set method providing array access
. I am not sure why.
e

ephemient

03/08/2021, 7:11 AM
Copy code
for (num1 in nums1) {
    outputMap[num1] = outputMap.getOrElse(num1) { 0 } + 1
}
s

Sudhir Singh Khanger

03/08/2021, 9:04 AM
Copy code
for (num2 in nums2) {
        outputMap[num2]?.let {
            if (it > 1) {
                outputList.add(num2)
                outputMap[num2] = it - 1
            }
        }
    }
Is
nums2[i] in outputMap && outputMap[nums2[i]] > 1
not working because the pair may not exist or have been changed after checking
containsKey.
Is there a way to improve the above code?
t

tDnamein

03/08/2021, 4:23 PM
If you want an intersection, you could do this:
Copy code
val nums1 = intArrayOf(1, 2, 2, 1)
val nums2 = intArrayOf(2, 2)

val setOfFirstArray =
        nums1.mapTo(hashSetOf()) { it }

 val intersection =
        nums2.filterTo(hashSetOf()) { n2 -> setOfFirstArray.contains(n2) }
This should even be quite efficient, since HashSet lookups are fast. Please have in mind, that in my understanding an intersection contains each element only once. If you have a different understanding the code above won't work for you.
j

Joel

03/08/2021, 10:13 PM
@tDnamein pretty sure this particular leetcode problem allows duplicates. There's always some catch in their problems.
s

Sudhir Singh Khanger

03/09/2021, 3:15 AM
@Joel There are two problems
349. Intersection of Two Arrays I
and
350. Intersection of Two Arrays II
. The latter one requires duplicate.
👍 1
19 Views