相关文章推荐
寂寞的海豚  ·  python - Sqlite3, ...·  1 年前    · 
气宇轩昂的硬盘  ·  JQuery的 ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.