我很难回答这个问题。所以我就用一个例子来说明。
假设我有以下数组:A = {5,8,1,3,2,6},大小为 n = 6,索引为 A[0...5]。
我想运行某种扫描,以便在从左到右的遍历中将每个值与其相邻的值进行比较。以下 2 个运行嵌套 for 循环的代码片段有什么区别?
// snippet 1, using i to take the first and j to take whatever is next to i.
for i <- 0 to n-2 do
for j <- i+1 to n-1 do
// do the scanning, comparing, etc....
//snippet 2 using i to take the first and j to take the second.
for i <- 0 to n-2 do
for j <- 1 to n-1 do
// do the scanning, comparing, etc....
我认为它们完全相同,并且在我所做的笔/纸测试中找不到任何差异。有吗?
最佳答案
在第一个中,j
从i
的下一个值开始计数。
示例:i = 1, j = 2
| i = 2, j = 3
等
在第二个中,无论 i
的值如何,您都将从 1 开始计数。换句话说,变量 i
对变量 j
没有影响。
两者都有各自的用途,但这完全取决于您如何使用它们来获取数组元素。
关于algorithm - 在嵌套 for 循环中使用 j= i+1 vs j = 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40897769/