编程问题:
某乐团的演出场地可视作 num * num 的二维矩阵 grid(左上角坐标为 [0,0]),每个位置站有一位成员。乐团共有 9 种乐器,乐器编号为 1~9,每位成员持有 1 个乐器。为保证声乐混合效果,成员站位规则为:自 grid 左上角开始顺时针螺旋形向内循环以 1,2,…,9 循环重复排列。
请返回位于场地坐标 [Xpos,Ypos] 的成员所持乐器编号。
示例:
- 输入:num = 3, Xpos = 0, Ypos = 2
输出:3 - 输入:num = 4, Xpos = 1, Ypos = 2
输出:5
解法:
1.数学
时间复杂度O(1)
空间复杂度O(1)
class Solution {
public:
int orchestraLayout(int num, int xPos, int yPos) {
int half = num / 2;
//外围层数
long cnt = min(xPos < half ? xPos : num - xPos - 1, yPos < half ? yPos : num - yPos - 1);
// 需要计算前cnt层的总数目
// 边长 a1 = num, an = num - (cnt - 1) * 2
// 带入 4 * 边长 - 4(减4是因为直接乘4重复使用了角上四个点) 来计算前cnt项和
// 即 4 * (num * cnt + cnt * (cnt - 1) * (-2) / 2) - 4 * cnt 化简
long index = 4 * cnt * (long)(num - cnt);
if (index + 1 == (long)num * num)
return ((index + 1) % 9) == 0 ? 9 : (index + 1) % 9;
int top = cnt, bottom = num - cnt - 1, left = cnt, right = num - cnt - 1;
// 坐标处于上面这条边
if (top == xPos)
{
index += yPos - left + 1;
return (index % 9) == 0 ? 9 : index % 9;
}
index += right - left + 1;
top++;
// 坐标处于右面这条边
if (right == yPos)
{
index += xPos - top + 1;
return (index % 9) == 0 ? 9 : index % 9;
}
index += bottom - top + 1;
right--;
// 坐标处于下面这条边
if (bottom == xPos)
{
index += right - yPos + 1;
return (index % 9) == 0 ? 9 : index % 9;
}
index += right - left + 1;
bottom--;
// 坐标处于左面这条边
if (left == yPos)
{
index += bottom - xPos + 1;
return (index % 9) == 0 ? 9 : index % 9;
}
return (index % 9) == 0 ? 9 : index % 9;
}
};