编程训练第九十九期——乐团占位

编程问题:

某乐团的演出场地可视作 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值