对,排序后,就是O(n)了。我自己写了一个,应该是对的。不过有点儿ugly. typedef struct { int start; int end; } Interval; int intcomp (const void * p1, const void * p2) { return *(int *)p1 - *(int *)p2; } Interval find_interval_cover(int a[], int N, int L) { Interval result; int i, j; int count = 0; qsort(a, N, sizeof(int), intcomp); print_arr(a, N); for (i = 0, j = 0; j < N; ) { if (a[j] <= a[i] + L) { j++; } else { if (j- i > count) { count = j - i; result.start = a[i]; result.end = a[i] + L; } i++; } } if (j- i > count) { count = j - i; result.start = a[i]; result.end = a[i] + L; } printf("count = %d\n", count); return result; }
【在 l*********8 的大作中提到】 : if the array is already sorted, O(n) algorithm can find the max coverage : interval. Just replace your binary search to sequential search. : : upper
maintain a BST with elements in current size L window, when you slide window from left to right, it amounts to one insertion and one deletion. So a balanced binary tree with extra count of each element will do it in O(logn) per move, and a total of O(nlogn)