From 55a4dfdbca50f266b2c1bf5fa4af1d2d31beeb6d Mon Sep 17 00:00:00 2001 From: xz-dev Date: Tue, 22 Sep 2020 17:59:38 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E9=A2=84=E6=B5=8B=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../net/xzos/upgradeall/utils/ListUtils.kt | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/net/xzos/upgradeall/utils/ListUtils.kt b/app/src/main/java/net/xzos/upgradeall/utils/ListUtils.kt index f480df69..b9bf2053 100644 --- a/app/src/main/java/net/xzos/upgradeall/utils/ListUtils.kt +++ b/app/src/main/java/net/xzos/upgradeall/utils/ListUtils.kt @@ -25,28 +25,46 @@ fun list1ToList2(list1: List, list2: List): List() + // 删除多余项 for (item in delList) { val index = tmpList.indexOf(item) operationSteps.add(ListDelOperationStep(index)) tmpList.removeAt(index) } + // 添加缺失项 + val addItemMap = hashMapOf() for (item in addList) { val index = list2.indexOf(item) if (index < tmpList.size) { tmpList.add(index, item) - operationSteps.add(ListAddOperationStep(index, item)) + addItemMap[item] = index } else { tmpList.add(item) - operationSteps.add(ListAddOperationStep(tmpList.size - 1, item)) + addItemMap[item] = tmpList.size - 1 } } + // 还原位置 + val swapItemMap = mutableMapOf>() for (i in tmpList.indices) { val item = tmpList[i] val newIndex = list2.indexOf(item) - if (i != newIndex && newIndex < tmpList.size) { + if (i != newIndex) { tmpList[i] = tmpList[newIndex].also { tmpList[newIndex] = tmpList[i] } - operationSteps.add((ListSwapOperationStep(i, newIndex))) + if (item in addItemMap) { + addItemMap[item] = newIndex + } else { + swapItemMap[item]?.let { + swapItemMap[item] = Pair(it.first, newIndex) + } ?: run { swapItemMap[item] = Pair(i, newIndex) } + } } } + val sorted = addItemMap.toList().sortedBy { (_, value) -> value }.toMap() + for ((item, index) in sorted.entries) { + operationSteps.add(ListAddOperationStep(index, item)) + } + for ((_, index) in swapItemMap) { + operationSteps.add((ListSwapOperationStep(index.first, index.second))) + } return operationSteps -} \ No newline at end of file +}