面试题答案
一键面试优化思路
- 缓存数组边界:在循环前计算并缓存数组的边界值,避免每次循环都进行边界判断。
- 减少不必要的计算:将一些固定的计算提到循环外部,避免重复计算。
- 动态分配资源管理:在动态分配内存(如使用
malloc
或new
)后,要确保在不再使用时及时释放,最好使用智能指针(如std::unique_ptr
)来自动管理内存,防止内存泄漏。
示例代码(C++)
#include <iostream>
#include <memory>
// 假设复杂计算函数
double weightedAverage(const double** arr, int i, int j, int rows, int cols) {
double sum = 0.0;
int count = 0;
for (int x = -1; x <= 1; ++x) {
for (int y = -1; y <= 1; ++y) {
int ni = i + x;
int nj = j + y;
if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) {
sum += arr[ni][nj];
count++;
}
}
}
return sum / count;
}
void optimizedTraversal(int rows, int cols) {
// 使用智能指针管理动态分配的二维数组
std::unique_ptr<double*[]> arr(new double*[rows]);
for (int i = 0; i < rows; ++i) {
arr[i] = new double[cols];
for (int j = 0; j < cols; ++j) {
arr[i][j] = i + j; // 初始化数据
}
}
// 缓存边界
int lastRow = rows - 1;
int lastCol = cols - 1;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
double result = weightedAverage(arr.get(), i, j, rows, cols);
std::cout << "Result at (" << i << ", " << j << ") : " << result << std::endl;
}
}
// 释放内存,智能指针会自动管理
}
你可以通过以下方式调用这个函数:
int main() {
optimizedTraversal(3, 3);
return 0;
}
示例代码(Python)
在Python中,由于其动态类型和垃圾回收机制,无需手动管理内存,但同样可以进行一些循环优化。
def weighted_average(arr, i, j, rows, cols):
sum_val = 0
count = 0
for x in range(-1, 2):
for y in range(-1, 2):
ni, nj = i + x, j + y
if 0 <= ni < rows and 0 <= nj < cols:
sum_val += arr[ni][nj]
count += 1
return sum_val / count
def optimized_traversal(rows, cols):
arr = [[i + j for j in range(cols)] for i in range(rows)]
last_row, last_col = rows - 1, cols - 1
for i in range(rows):
for j in range(cols):
result = weighted_average(arr, i, j, rows, cols)
print(f"Result at ({i}, {j}) : {result}")
if __name__ == "__main__":
optimized_traversal(3, 3)