微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Java中按索引查找第一对最大和

如何解决在Java中按索引查找第一对最大和

我有一个代码,其中我必须在两个相同长度的数组之间打印最大和的第一对索引。来自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);
    }
}

解决方法

我不确定为什么要在循环时打印出最大值,为什么循环六次(k = 6)而不是四次(即数组的长度)。我不理解您对 col count Flag 0 B 1 0 1 B 2 1 2 A 1 0 3 A 2 0 4 A 3 1 5 C 1 0 6 C 2 0 7 C 3 0 8 C 4 1 的使用,这是什么意思?

要更好地构建代码,请首先遍历数组之间的每个可能数字组合并计算总和。存储对最大和及其关联索引的引用。计算简单后,用索引打印出最大的和。在完成所有计算之后,必须这样做。

在代码中:

k

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。