Find the kth number in an array of sums

Given an array A with N elements, I need to find a pair (i, j), so I do not equal j and if we write the sum A [i] + A [j] for all pairs (i, j), then it falls into k-th position.

Example : let N = 4 and arrays A = [1 2 3 4], and if K = 3, then the answer will be 5, since we can clearly see that the total array looks like this: [3, 4,5,5 , 6.7]

I can’t use i and j for all pairs, since N can reach 100,000. Please help solve this problem.

I mean something like this:

int len=N*(N+1)/2;
int sum[len];
int count=0;
for(int i=0;i<N;i++){
   for(int j=i+1;j<N;j++){
        sum[count]=A[i]+A[j]; 
        count++;
   }
}
//Then just find kth element.

We cannot go with this approach.

+4
source share
3 answers

, http://www.careercup.com/question?id=7457663.

k 0, k- , setA + setB?, . O(n log(n)) , O(n), , O(k log(k)) . , k n*n - n.

k n*n/2, . http://en.wikipedia.org/wiki/Quickselect . O(n log(n)) . O(n) , . pivots O(log(n)). (, log(n*n) = O(log(n)).) , , O(log(n)) O(n log(n)) .

O(n log(n) log(n)).

: , . , .

, .

ArrayRangeWithAddend. , . array ( , ), a start end , a shiftValue , .

. size. partition(n) , n, , n, , n. value(i), i 'th .

ArrayRangeCollection. ArrayRangeWithAddend. , random partition(n) ArrayRangeCollection, n, , n, ArrayRangeCollection , n. partition ArrayRangeWithAddend 0.

ArrayRangeCollection, , . random partition , , .

0

, , K <= 50: K + 1 . . : , (i, j) , j > K + 1. K : (1, 2), (1, 3), ..., (1, K + 1). , K - .

O(N + K ^ 2) , K + 1, quickselect ( , ). O(N * log N + K ^ 2 * log K).

0

( ). , .

//A is the original array, such as A=[1,2,3,4]
//k (an integer) is the element in the 'sum' array to find

N = A.length

//first we find i
i = -1
nl = N
k2 = k
while (k2 >= 0) {
    i++
    nl--
    k2 -= nl
}

//then we find j
j = k2 + nl + i + 1

//now compute the sum at index position k
kSum = A[i] + A[j]

EDIT: . ... k 0. (, OP 1.)

2: . , sum 2D- ( ), ( OP) i j. , [1,2,3,4,5], sum :

3,4,5,6,
5,6,7,
7,8,
9.

- , i 0. - i 1. 'j', , .

... , !

0
source

All Articles