一.简介
上一章节讲述了使用DiffUtil工具类计算两个集合的差异。具体核心代码是calculateDiff方法。即 计算差异 的方法。
DiffUtil+AsyncListDiffer工具类原理讲解
https://blog.csdn.net/weixin_37730482/article/details/70772006
那么该方法中计算集合差异的算法是什么呢?我们从DiffUtil类的注释中可以看出来。
DiffUtil类的注释
DiffUtil is a utility class that calculates the difference between two lists
and outputs a list of update operations that converts the first list into the second one.
DiffUtil uses Eugene W. Myers's difference algorithm to calculate the minimal number of updates to convert one list into another.
Myers's algorithm does not handle items that are moved so DiffUtil runs a second pass on the result to detect items that were moved.
注释翻译
DiffUtil是一个计算两个列表之间差异的实用程序类
并输出一个更新操作列表,将第一个列表转换为第二个列表。
DiffUtil使用Eugene W. Myers的差分算法来计算将一个列表转换为另一个列表所需的最小更新数。
Myers的算法不处理被移动的项目,因此DiffUtil对结果进行第二次传递,以检测被移动的项目。
二.大致讲解
图解
这个算法的核心就成了如何从使用最少的步数从起点(0,0)走到终点(n,m)让这条线中尽可能多地包含对角线。
Myers 算法就是一个能在大部分情况产生”最短的直观的“ diff 的一个算法,算法原理如下。
首先,定义参数 d
和 k
,d 代表路径的长度,k
代表当前坐标 x - y
的值。定义一个”最优坐标“的概念,最优坐标表示 d 和 k 值固定的情况下,x 值最大的坐标。x 大,表示向右走的多,表示优先删除。
附
https://www.codeproject.com/Articles/42279/Investigating-Myers-diff-algorithm-Part-1-of-2
https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/