谁能告诉我上述代码之间的逻辑区别

时间:2018-07-27 16:34:08

标签: c algorithm

我无法弄清楚为什么在社论代码正常工作的情况下我的代码无法满足该问题的测试用例。


问题:

您位于无限的2D网格中,可以在8个方向中的任何一个上移动:

(x, y) to

(x+1, y), 
(x-1, y), 
(x, y+1), 
(x, y-1), 
(x-1, y-1), 
(x+1, y+1), 
(x-1, y+1), 
(x+1, y-1) 

系统会为您提供一系列的点以及覆盖这些点的顺序。给出实现它的最小步骤数。您从第一点开始。


输入:

给出两个整数数组AB,其中A[i]是第i个点的x coordinate,而B[i]是第i个点的y coordinate

输出:

返回整数(即最小步数)。

示例:

Input : [(0, 0), (1, 1), (1, 2)]
Output : 2

(0, 0) to (1, 1)移出仅一步。从(1, 1) to (1, 2)移出又需要一步。


我的代码:-

int coverPoints(int *A, int n1, int *B, int n2) {
    int count = 0, ele1 = 0, ele2 = 0, i;

    for (i = 0; i < n1 - 1; i++) {
        ele1 = abs(A[i+1] - A[i]);
        ele2 = abs(B[i+1] - A[i]);
        if (ele1 > ele2) {
            count += ele1;
        } else {
            count += ele2;    
        }
    }
    return count;
}

版本解决方案:-

int coverPoints(int *X, int n1, int *Y, int n2) {
    int stepsx = 0, stepsy = 0, diffx = 0, diffy = 0, steps = 0;
    int i = 0;

    for(i = 0; i < (n1-1); i++) {
        diffx = X[i+1] - X[i];
        if (diffx < 0)
            diffx = diffx * (-1);
        //stepsx = stepsx + diffx;

        diffy = Y[i+1] - Y[i];
        if (diffy < 0)
            diffy = diffy * (-1);
        //stepsy = stepsy + diffy;

        if (diffx > diffy)
            steps = steps + diffx;
        else
            steps = steps + diffy;
    }

    return steps;
}

无效的测试用例为:-

A : [ 4, 8, -7, -5, -13, 9, -7, 8 ]
B : [ 4, -15, -10, -3, -13, 12, 8, -8 ]

expected output = 108
my output = 105

2 个答案:

答案 0 :(得分:3)

此行有问题

ele2 = abs(B[i+1]-A[i]);

diffy = Y[i+1] - Y[i];

它将是:

ele2 = abs(B[i+1]-B[i]);

答案 1 :(得分:1)

ele2 = abs(B[i+1] - A[i]);中有一个复制+粘贴错字。该代码应为:

ele2 = abs(B[i+1] - B[i]);