没看懂,还是多谢code了。测试了一下,貌似second max不对。。。不管k换成3还是4 ,都给第一个72,第二个是69,第三个是70. int main() { int a[10]={39,31,34,53,24,70,42,69,72,44}; int *p; int size = 0; p = findPath(a,0,10,size); cout<cout<cout<cout<getchar(); return 1; }
【在 j*****y 的大作中提到】 : 写了一个 code ,不过需要 O((log n)) 的 extra space : first get k = log n; : int * findPath(int A[], int start, int end, int & size) : { : if(start == end) : { : int *result = new int[k]; : result[0] = A[start]; : size = 1; : return result;
【在 c********t 的大作中提到】 : 理论上是,但实际上 最普通的走一遍算法平均也是 n+n/2次比较,因为if a[i] > : current max then it doesn't need to compare with the current second max. : best is n, worst is 2n.
arr=[10,9,8,7,6,5,4,3] first=arr[0..1].max second=arr[0..1].min (2...arr.length).each do |i| if arr[i]>second if(arr[i]>first) second=first first=arr[i] else second=arr[i] end end end p first p second
c*t
18 楼
明白了,多谢! 把你说的扩展为n,要开至少n空间,存所有path,(用map好些)divide and conquer, (如果每次不释放被conquer的数的path的话,还需要更多空间)最后留下最大数,和 它的path,这时候的path应该是lgn的。理论上比较次数为 n+lgn-1,但是存储读写次 数增加很多,时间优化了吗?