该题为数学问题,若采用暴力方法,时间复杂度太高,不能满足。具体数学思想如下:
将方阵分为不同的圈,先计算出要求的点所在第几个圈中,然后可以计算出每层圈的周长,最后根据所求出要计算的点在最后一个圈内的什么位置,进而得到所有圈的周长之和,再余9即可求出答案。
不难得出,点处于的位置在
circle = min({ xPos, num - 1 - xPos, yPos, num - 1 - yPos });
每条边的边长为
side = num - 1
最里面一个完整圈的边长是num - 1 - (circle - 1) * 2 = num - 2 * circle + 1
这些圈的周长是等差数列,所以总共:
seq = 4 * (num - 1 + num - 2 * circle + 1) * circle / 2 = 4 * (num - circle) * circle
最后根据嘴里边的圈左上角的坐标为vertex = {circle, circle},进行判断。
class Solution {
public:
int orchestraLayout(int num, int xPos, int yPos) {
long long circle;
long long side;
circle = min(min(xPos, num-xPos-1),min(yPos,num-yPos-1));
side =num - 2 * circle -1;
long long seq = 4 * (num -circle) * circle;
long long xVertex = circle, yVertex = circle;
if(xPos == xVertex && yPos < yVertex + side){
seq += ((long long)yPos + 1 - circle);
}
else{
seq+=side;
if(yPos == yVertex + side && xPos < xVertex + side){
seq += ((long long)xPos + 1 - circle);
}
else{
seq += side;
if(xPos == xVertex + side && yPos > yVertex){
seq += (yVertex + side + 1 - yPos);
}
else{
seq += (side + xVertex + side + 1 - xPos);
}
}
}
seq %= 9;
return (int)(seq == 0? 9 :seq);
}
};
参考如下:
作者:wen-rou-yi-dao-123
链接:https://leetcode.cn/problems/SNJvJP/solution/tu-wen-bing-mao-jiang-jiang-shu-xue-fang-dt8e/