Sudhir Singh Khanger
03/08/2021, 4:12 AMpackage 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.ephemient
03/08/2021, 7:11 AMfor (num1 in nums1) {
outputMap[num1] = outputMap.getOrElse(num1) { 0 } + 1
}
Sudhir Singh Khanger
03/08/2021, 9:04 AMfor (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?tDnamein
03/08/2021, 4:23 PMval 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.Joel
03/08/2021, 10:13 PMSudhir Singh Khanger
03/09/2021, 3:15 AM349. Intersection of Two Arrays I
and 350. Intersection of Two Arrays II
. The latter one requires duplicate.