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

oday

11/06/2020, 10:59 AM
does
in
cause the runtime of the program to become as if it were 2 for loops O(n2)?
t

Tobias Berger

11/06/2020, 11:17 AM
in
in this case is just syntactic sugar for
contains
, so line 7 is the same as
if (values.contains(difference)) {
. What happens inside of the contains-Function depends on the map implementation (here a LinkedHashMap)
o

oday

11/06/2020, 12:09 PM
so map access is O(1)
so this is O(n)
n

nanodeath

11/06/2020, 5:23 PM
so because this is Kotlin, they should be basically the same, but normally (e.g. Java)
contains
and
.get(...) != null
can be different because values can be null. but because it's Kotlin, they're basically equivalent
also btw I'd use the infix
to
instead of
Pair
...usually looks nicer
also you might say
values[difference]?.let { return index to it }
(or something like that), as that'll save you the trouble of doing the lookup in
values
twice
2 Views