【发布时间】:2015-11-13 01:10:58
【问题描述】:
我想从一个总和等于 10 的数组中找到所有的数字对,并尝试在此处改进这段代码:
for (int j = 0; j < arrayOfIntegers.length - 1; j++)
{
for (int k = j + 1; k < arrayOfIntegers.length; k++)
{
int sum = arrayOfIntegers[j] + arrayOfIntegers[k];
if (sum == 10)
return j + "," + k;
}
}
但是,我无法在阵列中移动。这是我到目前为止所拥有的:
int[] arrayOfIntegers = {0, 5, 4, 6, 3, 7, 2, 10};
Arrays.sort(arrayOfIntegers);
System.out.println(Arrays.toString(arrayOfIntegers));
int left = arrayOfIntegers[0];
int right = (arrayOfIntegers[arrayOfIntegers.length - 1]);
while (left < right)
{
int sum = left + right;
if (sum == 10) //check to see if equal to 10
{
System.out.println(left + "," + right);
}
if (sum > 10) // if sum is more than 10, move to lesser number
{
right --;
}
if (sum < 10) // if sum is less than 10, move to greater number
{
left++;
}
} // end of while
【问题讨论】:
-
请格式化您的代码。这是难以辨认的。
-
你为什么这样做:
if sum > 10 then right--, if sum < 10 then left++?您的左右是 value 而不是 index 到数组。即使它们是索引,你的数组也没有排序,这样做没有意义 -
你到底想“改进”什么?...