计算Kth和

时间:2015-04-04 19:55:41

标签: arrays algorithm sorting

我的问题是这样的: 我有一个数字N <= 50000和一个带有N个元素的数组A. A中的值是从0到2 ^ 21的正数。 我需要计算所有和A [i] + A [j],其中0 <= i,j <1。 N(i可以等于j,因此A [1] + A [1]是有效和)。 然后我需要对总和进行排序并检索Kth和(其中K是给定值)。

示例:

N = 3
K = 4
A = [7, 2, 5]

以下总结出现:

2 + 2 = 4
2 + 5 = 7
5 + 2 = 7
2 + 7 = 9
7 + 2 = 9
5 + 5 = 10
5 + 7 = 12
7 + 5 = 12
7 + 7 = 14

Kth sum是第4:2 + 7 = 9

理想情况下,我希望复杂性为 O(n * log n),所以我想避免计算所有总和的粗略方法,对它们进行排序并检索Kth值。

我做的第一件事是对数组进行排序,我使用了合并排序。

但是,我不确定如何继续进行,哪种算法更适合我的任务。

从我的观点来看,这有点棘手,我做了一些适用于某些值的东西,但当我尝试更多数字(例如20)时,它开始失败。因此,我的解决方案可能不是我应该做的。

下面你可以看到我到目前为止做了什么(没有排序,我只是在代码中硬编码了一个排序的数组):

import java.util.*;

public class KthSum {
    public static void main(String args[]) {
        Integer numbersCount = 3;

        ArrayList<Integer> sortedList = new ArrayList<Integer>();
        sortedList.add(2);
        sortedList.add(5);
        sortedList.add(7);
        sortedList.add(9);
        sortedList.add(10);
        sortedList.add(13);
        sortedList.add(14);
        sortedList.add(16);
        sortedList.add(17);
        sortedList.add(20);
        sortedList.add(21);
        sortedList.add(26);
        sortedList.add(32);
        sortedList.add(33);
        sortedList.add(34);
        sortedList.add(41);

        Integer desiredSumIndex = 153;

        Integer i = 0,
                j = 0,
                sumIndex = 0;

        while (sumIndex < desiredSumIndex) {
            Integer sum1 = 0;
            Integer sum2 = 0;
            if (i == j) {
                sumIndex++;
                if (sumIndex >= desiredSumIndex) break;
                j++;
            } else {
                sumIndex++;
                if (sumIndex >= desiredSumIndex) break;
                sumIndex++;
                if (sumIndex >= desiredSumIndex) {
                    Integer k = i;
                    i = j;
                    j = k;
                    break;
                }
                sum1 = i < numbersCount - 1 ? sortedList.get(i + 1) * 2 : 0;
                sum2 = j < numbersCount - 1 ? sortedList.get(i) + sortedList.get(j + 1) : sum1 + 1;

                if (sum1 < sum2) {
                    i++;
                    j = i;
                } else {
                    j++;
                }
            }
        }

        Integer outputSum = sortedList.get(i) + sortedList.get(j);

        System.out.println(String.format("The sum is %d and it is composed from the positions %d and %d", outputSum, i, j));
    }
}

我需要任何帮助。欢迎所有想法:)

干杯, 亚历

0 个答案:

没有答案