leedcode 396:Rotate Function

来源:互联网 发布:linux下qt串口编程 编辑:程序博客网 时间:2024/04/27 14:13

Given an array of integers A and let n to be its length.

Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow:

F(k)=0*Bk[0]+1*Bk[1]+...+(n-1)*Bk[n-1].

Calculate the maximum value of F(0), F(1), ..., F(n-1).

Note:
n is guaranteed to be less than 105.

Example:

A = [4, 3, 2, 6]F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

初步想法:

int maxRotateFunction(int* A, int ASize) {    int F[ASize];    int i;    int j;    int temp=0;    if(ASize==0)return 0;    for(i=0;i<ASize;i++){       F[i]=0;    }    for(i=0;i<ASize;i++){        for(j=0;j<ASize;j++){            temp=(ASize-j+i)%ASize;            F[j]+=i*A[temp];        }    }    temp=F[0];    for(i=1;i<ASize;i++){       temp=temp>F[i]?temp:F[i];    }        return temp;}

时间复杂度为O(n2),timeout。

最开始只想到每算出一个F[k],时间复杂度为O(n),算出n个时间复杂度也只能是O(n2),于是就想当然的没有再考虑时间复杂度的问题,按照最原始的方法算出每一个F[k],然后再比较大小,最终结果果然是timeout。

于是看了别人的解答,解题思路为找出F[K]与F[k-1]之间的关系,先计算出F[0],再根据F[0]计算出剩下的F,这样时间复杂度为O(n)。

F[k]=0*Bk[0]+1*Bk[1]+...+(n-1)*Bk[n-1]

F[k-1]=0*Bk-1[0]+1*Bk-1[1]+...+(n-1)*Bk-1[n-1]

      =0*Bk[1]+1*Bk[2]+...+(n-2)*Bk[n-1]+(n-1)*Bk[0]

F[k]-F[k-1]=(1-n)*Bk[0]+Bk[1]+Bk[2]+...+Bk[n-1]

   =sum-n*Bk[0]

其中sum为数组中所有数的和;

Bk[0]的计算方式为:

k=0, Bk[0] = A[0];

k=1, Bk[0]= A[ASize-1];

......

k=n-1, Bk[0] = A[ASize-(n-1)] 

实现如下:

int maxRotateFunction(int* A, int ASize) {    int f=0;    int sum=0;    int result=0;    int i;    for(i=0;i<ASize;i++){        f+=i*A[i];        sum+=A[i];    }    result=f;    for(i=1;i<ASize;i++){        f=sum-ASize*A[ASize-i]+f;        result=result>f?result:f;    }    return result;}

总结:思考问题的时候不要被固有思维局限,多方面考虑。

0 0
原创粉丝点击