答案可能很明显,但是即使在谷歌搜索之后,我仍然可以找到解决此问题的正确方法。我知道我必须在函数的末尾添加return语句,以便它可以完成,但是什么样的呢?
以下程序实现了一种算法,该算法可在数组列表中找到第i个最小元素
public int search(ArrayList<Integer> a, int i){
ArrayList<Integer> smaller_than = new ArrayList<Integer>();
ArrayList<Integer> greater_than = new ArrayList<Integer>();
int pivot = a.get(i);
for(int j = 0; j < a.size(); j++) {
if (a.get(j) <= pivot){
smaller_than.add(a.get(j));}
if (a.get(j) > pivot){
greater_than.add(a.get(j));}}
if (smaller_than.size() == i)
return smaller_than.get(i);
else if (smaller_than.size() < i)
return search(greater_than, i-smaller_than.size());
else if (smaller_than.size() > i)
return search(smaller_than, i);
}
我显然不能在末尾添加return null,那么您可以帮助我找到解决方案吗?
只需将最后一个if else
转向a,else
因为如果它不相同或较小,则必须更大:
if (smaller_than.size() == i)
return smaller_than.get(i);
else if (smaller_than.size() < i)
return search(greater_than, i-smaller_than.size());
else
return search(smaller_than, i);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句