Reputation: 195
I am trying to write a function to find the majority element in kotlin but when I compile the code I get variable expected error on the following line
map[key]?.let{ value->
Below is the function which I am trying to run. I am new to Kotlin and not sure why I am getting this error.
fun majorityElement(nums: IntArray): Int {
HashMap<Int,Int>().let{ map ->
nums.forEach{ key->
map[key]?.let{ value->
map[key]=value+1
}?:map[key]=1
}
map.forEach{entry->
if(entry.value>nums.size/2){
return entry.key
}
}
}
return -1
}
Upvotes: 2
Views: 6249
Reputation: 23125
Basically the problem is in this part:
map[key]?.let { ... } ?: map[key] = 1
Here the expression is parsed not the way you might expect. map[key]?.let { ... } ?: map[key]
becomes an l-value of the assignment operator and 1
becomes an r-value.
The l-value of an assignment must be something that you can assign a value to, i.e. a variable, a property, an indexer, like map[key] =
, but here it is a complex expression
map[key]?.let { ... } ?: map[key]
.
If you want to execute assignment only when map[key]
is null, you can wrap that statement in run
function:
map[key]?.let { ... } ?: run { map[key] = 1 }
Perhaps it would be more clear to rewrite this block the following way:
// get value associated with key or 0 if there is none.
map[key] = map.getOrElse(key, { 0 }) + 1
Looking from a higher perspective, it seems that you need to count the occurrences of numbers in an array of ints. For that case a more high-level approach with groupingBy
and eachCount
functions can be used:
val map = nums.asList().groupingBy { it }.eachCount()
// then find the majority in this map
Upvotes: 5