我正在编写一个程序,我似乎无法进行IF动作循环并检查主程序中的所有数组。我的工作是弄清楚这个升序排序数组中是否存在任何数字对(即任意两个元素),最多可加20个。所有你需要做的就是将这两个指针指向的值相加并查看是否它们等于20,如果是,则输出。否则,检查总和,如果总和大于20,则递减第二个指针,如果总和小于20,则递增第一个指针。不能使用嵌套for循环方法!!不确定如何解决这个问题...我已经在这里工作了几个小时并且手写它没有运气。谢谢!!
// if val of arr at index i is smaller than at arr j, then return
// smaller value
// This function will inspect the input to find any pair of values that
// add up to 20
// if it find such a pair, it will return the *index* of the smallest
// value
// if it does not find such as pair, it will return -1;
public class SumExperiment {
public static int check_sum(int[] array) {
int i = array[0];
int y = array.indexOf(array.length); // need value @ index of array.length to begin
//loop to repeat action
for (int arraysChecked = 0; arraysChecked < 5; arraysChecked++ )
{
if ( i + y == 20)
{
return i;
// System.out.print(array[i]);
}
else if ( i + y > 20)
{
y--; //index @y
}
else if (i + y < 20)
{
i++; //index @x
}
if ( i + y != 20)
{
return -1;
}
arraysChecked++;
}
return -1; //because must return int, but this isn't correct
}
public static void main(String[] args) {
int[] array1 = new int[] { 5, 7, 8, 9, 10, 15, 16 };
if (check_sum(array1) != 0)
System.err.println("TEST1 FAILED");
int[] array2 = new int[] { 3, 5, 8, 9, 10, 15, 16 };
if (check_sum(array2) != 1)
System.err.println("TEST2 FAILED");
int[] array3 = new int[] { 3, 4, 6, 9, 10, 14, 15 };
if (check_sum(array3) != 2)
System.err.println("TEST3 FAILED");
int[] array4 = new int[] { 6, 7, 8, 9, 10, 15, 16 };
if (check_sum(array4) != -1)
System.err.println("TEST4 FAILED");
System.out.println("Done!!!");
}
}
答案 0 :(得分:1)
我认为你在数组中的值和值的索引之间感到困惑。这是一个带有变量名称的工作版本,可以更容易地理解正在发生的事情:
public static int check_sum(int[] array) {
int leftIndex = 0;
int rightIndex = array.length - 1;
for (int arraysChecked = 0 ; arraysChecked < 5 ; arraysChecked++) {
if (leftIndex == rightIndex) {
return -1;
}
int smallerValue = array[leftIndex];
int largerValue = array[rightIndex];
int sum = smallerValue + largerValue;
if (sum == 20) {
// Returns INDEX of smaller value
return leftIndex;
} else if (sum > 20) {
rightIndex--;
} else if (sum < 20) {
leftIndex++;
}
// NO NEED FOR THIS: arraysChecked++; (for loop does it for you)
}
}