【发布时间】:2021-01-18 01:03:46
【问题描述】:
我有一个代码,我必须在其中打印两个相同长度的数组之间最大和的第一对索引。来自 arr1 的第一个值 i 和来自 arr2 的第二个值 j。我成功地找到了最大值为 7 的值对及其索引(有两对总和为 7)。但我只需要打印最接近数组第一个元素的最大和的第一对。
import java.util.ArrayList;
import java.util.List;
class maximal_sum
{
static void kLargestPair(int[] arr1, int n1, int[] arr2, int n2, int k)
{
if (k > n1*n2)
{
System.out.print("k pairs don't exist");
return ;
}
int index2[] = new int[n1];
while (k > 0)
{
int max_sum = Integer.MIN_VALUE;
int max_index = 0;
for (int i1 = 0; i1 < n1; i1++)
{
if (index2[i1] < n2 &&
arr1[i1] + arr2[index2[i1]] > max_sum)
{
max_index = i1;
max_sum = arr1[i1] + arr2[index2[i1]];
List<int[]> result = new ArrayList<int[]>();
result.add(new int[]{arr1[max_index],arr2[index2[max_index]]});
if(index2[max_index] > max_index) {
System.out.print("(" + arr1[max_index] + ", " +
arr2[index2[max_index]] + ") ");
//here prints the pair of values: (6,1) (4,3)
//we just need to print (4,3) because it comes before (6,1) according to the indices
System.out.print("(" + max_index + ", " +
index2[max_index] + ") ");
//here prints the pair of indices: (2,3) (0,1)
//we just need to print (0,1) because it comes before (2,3) according to the indices
}
}
}
index2[max_index]++;
k--;
}
}
public static void main (String[] args)
{
int[] arr1 = {4, -8, 6, 0};
int n1 = arr1.length;
int[] arr2 = {-10 ,3, 1, 1};
int n2 = arr2.length;
int k = 6;
kLargestPair( arr1, n1, arr2, n2, k);
}
}
【问题讨论】:
标签: java arrays list arraylist indices