Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
幼稚的方法
是一种天真的方法是使用
使用
,以通过匹配名称检索元素的索引。然后在第一个列表上应用concamingInt()
创建sort()
。如果
equals()
和hashcode()
不仅基于name
属性,我们可以创建一个包装程序类并实现其<代码>等于/hashcode 合同的方式仅在比较期间考虑name
。然后基于
list1
和list2
生成两个列表employeewrapper
对象(下面的代码不完整,仅提供以说明这个想法)。但是,多次迭代第二列表第二列表将非常低效。确切地说,时间复杂性将为 o(m * n log n)(其中
n
- 第一个列表中的元素数,m
- 第二列表的大小)。由于第二个列表中的元素位置不会更改,因此在地图中存储索引
,我们可以单个通过列表中的索引并将其存储在 map 中。然后基于此 map 生成A 比较器。
时间复杂性将为 o(m + n log n)(这是指第二列表的影响要高得多)。
main()
在某些条件下,可以进一步优化此代码。
例如,如果没有重复的名称,则可以使其在A 线性时间中运行。
Naive approach
A naive way would be to create
Comparator
usingcomparingInt()
by the logic for retrieving the indexed of the element with the matching name. And then applysort()
on the first list.In case if
equals()
andhashCode()
are not based on thename
property only, we can create a wrapper class and implement itsequals/hashCode
contract in such a way that onlyname
will be taken into account during comparison.And then based on the
list1
andlist2
generate two listsEmployeeWrapper
objects (the code below is incomplete and provided only to illustrate the idea).But it would be terribly inefficient to iterate over the second list multiple times. To be precise, time complexity would be O(m * n log n) (where
n
- number of elements in the first list,m
- the size of the second list).Storing indices in the Map
Since the positions of the elements in the second list don't change, we can index them in a single pass through the list and store it in the map. And then generate a comparator based on this map.
The time complexity would be O(m + n log n) (it means the impact of the second list far more moderate).
main()
In certain conditions, this code can be optimized further.
For instance, if there would be no duplicated names, it's possible to make it run in a linear time.