Codility算法测验(二)

接上篇博文,这是第二个题目。     

A 2D Cartesian plane is given. A lattice point in this plane is a point whose coordinates are integers. All lattice points of the plane are arraged into a spiral as follows:
point (0, 0) is point number 0;
point (0, 1) is point number 1;
point (1, 1) is point number 2;
thereafter the points are (1, 0), (1, -1), (0, -1),  (-1, -1), (-1, 0), (-1, 1), (-1, 2), (0, 2), (1, 2), (2, 2), (2, 1) etc. 
图片
Every lattice point is included in the spiral, so it can be described either by its Cartesian coordinates or by its spiral coordinate, i.e. its number on the spiral.
That, given two integers X and Y, return the spiral coordinate of the lattice point (X, Y). 

Assume that:
        X and Y are integers  within the range [-20,000..20,000]
Complexity:
        expected worst-case time complexity is O(1);
        expected wors-case space complexity is O(1). 

思考: 我数学不好,不知道这种螺旋点是否有更简单统一的公式没有。只好用了最笨的办法,分四个象限,每个象限有分别判断,写了一个很笨的函数。然后从零点走起,一个一个的数上去。

public int solution(int X, int Y) {
    int ans = 0;
    int mX = 0, mY = 0;
    int[] next = new int[2];
    while (mX != X || mY != Y) {
        next = getNextPoint(mX, mY);
        mX = next[0];
        mY = next[1];
        if (Math.abs(mX) > 20000 || Math.abs(mY) > 20000) return -1;
        ans++;
    }
    return ans;
}
private int[] getNextPoint(int X, int Y) {
        int[] ans = new int[2];
        //以下逻辑可能有碍码容。脑子不灵光,实在没办法
        if (X <= 0 && Y >= 0) {
            if (Math.abs(X) < Math.abs(Y)) {
                ans[0] = X + 1;
                ans[1] = Y;
            } else {
                ans[0] = X;
                ans[1] = Y + 1;
            }
        } else if (X >= 0 && Y >= 0) {
            if (Math.abs(X) < Math.abs(Y)) {
                ans[0] = X + 1;
                ans[1] = Y;
            } else {
                ans[0] = X;
                ans[1] = Y - 1;
            }
        } else if (X >= 0 && Y <= 0) {
            if (Math.abs(X) <= Math.abs(Y)) {
                ans[0] = X - 1;
                ans[1] = Y;
            } else {
                ans[0] = X;
                ans[1] = Y - 1;
            }
        } else if (X <= 0 && Y <= 0) {
            if (Math.abs(X) < Math.abs(Y)) {
                ans[0] = X - 1;
                ans[1] = Y;
            } else {
                ans[0] = X;
                ans[1] = Y + 1;
            }
        }
        
        return ans;
    }

 

你可能感兴趣的:(算法,codility)