【发布时间】:2011-12-04 22:14:06
【问题描述】:
我遇到了一些严重的问题。我需要一个“分而治之”的递归算法,它告诉我最长的非递减数字数组的长度。就个人而言,我会选择使用我在仔细阅读问题之前编写的这段代码。
int bestIndex = 0;
int bestLength = 0;
int curIndex = 0;
int curLength = 1;
for (int i = 1; i < a.length; i ++){
if (a[i] >= a[i-1]){
curLength ++;
}else {
curLength = 1;
curIndex = i;
}
if (curLength > bestLength){
bestIndex = curIndex;
bestLength = curLength;
}
}
return bestLength;
问题是任务要求我使用分而治之,我想不出一种方法来做到这一点。
例如“4 2 3 3 1 2 4 5 9 2” 由于“1 2 4 5 9”,它将返回“5”
非常感谢任何帮助。
谢谢
【问题讨论】:
-
遍历列表,选择“分裂点”作为减少的地方。但是,除非您在中间附近选择一个分割点,否则这不会真正“分割”。我会从中间开始,然后向外迭代。循环 i= m(中间),然后是 m-1、m+1、m-2、m+2 等,直到 i 和 i+1 之间减少。然后在那里将数组切成两半并在每一半上递归。当不存在减数时,返回序列的长度。
标签: algorithm