我需要检查矩阵主对角线上的元素是否为偶数且可整除为其索引总和。我记得一维数组中的此类元素:
for (i=0; i<n; ++i)
for (j=0; j<m; ++j)
{
if ((i == j) && ((arr[i][j] % 2) == 0))
{
arr2[count] = arr[i][j];
++count;
break;
}
}
然后我用满足条件的元素替换为其索引的总和,并为[0] [0]设置特殊条件,因为除以0:
count = 0;
for (i=0; i<n; ++i)
for (j=0; j<m; ++j)
{
if ((i+j != 0) && (arr[i][j] == arr2[count]) && ((arr[i][j] % (i+j)) == 0))
{
arr[i][j] = i+j;
++count;
}
else if (((i+j) == 0) && (arr[i][j] == arr2[count])) arr[i][j] = 0;
}
麻烦的是,当第一个元素为偶数时,它是唯一替换的数字,而该条件不适用于其他元素:
答案 0 :(得分:3)
arr2
未正确填写。一旦将一个元素填充到其中,就会脱离该循环。注意该循环中break
的用法。而且,在这种else-if条件下,您没有更新count
的值,这会导致您的循环始终徒劳地搜索arr2[0]
。
删除该break
语句。
将++count
添加到else-if条件中。
奖金:
您编写了难看的代码。您使用了一个额外的数组,这增加了代码的空间复杂度,并且循环太多,也增加了时间复杂度。以后您会逐渐了解这些内容,但现在,我会为您提供更好的解决方案:
// Deal with the (0, 0) case outside the loop
// And avoid an extra else-if inside the loop
if (arr[0][0] % 2 == 0)
arr[0][0] = 0;
// There are n diagonal elements in a matrix of order n
// Row and column indexes of a diagonal element are equal
// So you can eliminate the use of j and just rely on i
for (i = 1; i < n; ++i)
// Check if the diagonal element is even and divisible by the sum of the indices
if (arr[i][i] % 2 == 0 && arr[i][i] % (i + i) == 0)
// Replace the element if the condition is satisfied
arr[i][i] = i + i;
如您所见,这种方法不需要任何额外的空间,并且可以在非常好的线性时间内运行。您可以通过按位与!(i & 1)
检查数字是否为奇数,并将i + i
更改为2 * i
来进一步优化它,这可以使用按位左移运算符{{1}快速完成}。
顺便问一下,为什么要替换(i << 1)
? Division by 0 is undefined。