How to move specific item in array list to the first item

前端 未结 6 1439
别跟我提以往
别跟我提以往 2020-12-08 13:03

For example : A list

A B C D E

Given C , Switch to

C A B D E

Notice that the array size will change, some items may removed in run times

6条回答
  •  眼角桃花
    2020-12-08 13:35

    Another solution, just keep swaping from 0 to indexOf(itemToMove).

    This is my Kotlin version:

    val list = mutableListOf('A', 'B', 'C', 'D', 'E')
    (0..list.indexOf('C')).forEach {
        Collections.swap(list, 0, it)
    }
    

    Sorry I am unfamiliar with Java but learned a little Kotlin. But the algorithm is the same.

提交回复
热议问题