[英]Merging two sorted ArrayLists
我應該創建一個將兩個給定的預先排序的字符串ArrayList合並為一個的方法。 所有這些都必須在一個循環中完成。 我解決的方法是比較每個索引處的兩個ArrayList,並根據這些比較以字母順序將它們添加。 這樣做的問題是,如果給您兩個ArrayLists [“ Bob”,“ Jill”]和[“ Watson”,“ Zane”],則輸出為[“ Bob”,“ Watson”,“ Jill”,“贊恩“。 這顯然沒有排序。
話雖如此,我知道問題出在哪里,我只是不知道如何實現此問題的解決方案。
碼:
public static ArrayList<String> merge(ArrayList<String> al1, ArrayList<String> al2){
ArrayList<String> al = new ArrayList<String> (al1.size() + al2.size());
for (int i = 0; i < Math.max(al1.size(), al2.size()); i++) { // Loops until max size of the two arraylists is reached
if (i < al1.size() && i < al2.size()) { // Checks if the index is still in range of both arraylists
if (al1.get(i).compareTo(al2.get(i)) < 0) { // Compares the two arraylists at the same index
al.add(al1.get(i));
al.add(al2.get(i));
} else {
al.add(al2.get(i));
al.add(al1.get(i));
}
} else if (i < al1.size() && i > al2.size()) { // Checks if the index is greater than the size of al2
al.add(al1.get(i));
} else { // Anything else, just add al2
al.add(al2.get(i));
}
}
return al;
您正在使用一個索引i
來索引a1
和a2
,這意味着您不能獨立瀏覽兩個列表。 正如您所注意到的,應該合並兩個列表,例如[1, 2, 3]
和[4, 5, 6]
,方法是從第一個列表中獲取所有三個元素, 然后從第二個列表中獲取元素。 在執行操作時同時遍歷兩個列表是不可能的。
而是跟蹤兩個單獨的索引,例如i1
和i2
,並分別遞增它們。 在每次迭代中,確定哪個索引較小,然后添加該值並遞增該索引。 到達一個列表或另一個列表的末尾時,您就耗盡了其余列表。
您應該查看合並排序算法的合並步驟: https : //en.wikipedia.org/wiki/Merge_sort
總之,您應該具有以下內容:
int i = 0;
int j = 0;
while (i < a.size() && j < b.size()) {
if (a.get(i).compareTo(b.get(j)) <= 0) {
result.add(a.get(i));
++i;
} else {
result.add(b.get(j));
++j;
}
}
for (; i < a.size(); ++i) {
result.add(a.get(i));
}
for (; j < a.size(); ++j) {
result.add(b.get(j));
}
return result;
沒測試過,但是結果你應該有看起來一樣的東西
public static ArrayList<Double> merge(ArrayList<Double> a, ArrayList<Double> b) {
ArrayList<Double> toReturn = new ArrayList<Double>();
int a_ = 0;
int b_ = 0;
for(int j = 0; j < a.size() + b.size(); j++) {
if(a_ == a.size())
toReturn.add(b.get(b_++));
else if(b_ == b.size())
toReturn.add(a.get(a_++));
else if(a.get(a_).compareTo(b.get(b_)) < 0)
toReturn.add(a.get(a_++));
else
toReturn.add(b.get(b_++));
}
return toReturn;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.