题目:
坐标轴上从左到右依次的点为a[0]、a[1]、a[2]……a[n-1],设一根木棒的长度为L,求L最多能覆盖坐标轴的几个点?
思路:
这是一道简单的数组题,
方法也很简单:直接从左到右扫描,两个指针i和j,i从位置0开始,j从位置1开始,如果a[j] - a[i] <= L(采用<=,是因为可能某个区间不能刚好等于L),则j++,并记录中间经过的点个数,如果a[j] - a[i] > L,则j--回退,覆盖点个数-1,回到刚好满足条件的时候,将满足条件的最大值与所求最大值比较,然后i++,j++,直到求出最大的点个数(结果可能有多种情况,只取第一次满足的情况)。
代码:
#include<iostream> using namespace std; int maxCover(int a[],int n,int L){ int i=0,j=1; int count=1,maxCount=1,start; while(i<n && j<n){ while((j<n) && (a[j]-a[i]<=L)){ j++; count++; } j--; if(maxCount<count){ maxCount=count; start=i; } i++; j++; count--; } cout<<"Covered points: "; for(int i=start;i<start+maxCount;i++) cout<<a[i]<<" "; cout<<endl; return maxCount; } int main() { // test int len; int L=8; int a[] = { 1, 3, 6, 8, 9,10, 11, 12, 13, 15, 16, 17, 18 }; len=sizeof(a)/sizeof(a[0]); cout<<"max count: "<<maxCover(a,len,L)<<endl;; int b[] = { 1, 2, 3, 4, 5, 100, 1000 }; len=sizeof(b)/sizeof(b[0]); cout<<"max count: "<<maxCover(b,len,L)<<endl; return 0; }