C ++ check of this condition in O (nlog (n)) time?

Suppose you have a sorted vector {x i } i = 1 n whose elements are all positive and do not contain tie (= no the two elements in this vector are the same).

I am looking for the smartest way to verify that:

2x i - x j - x k ! = 0 for all 1 <= i! = J! = K <= n.

I have a hunch that this can be done in time O (nlog n) or otherwise better than naive time, perhaps using a strategy similar to that developed in the answers to this question .

Recall that the entries x are all positive and sorted, so entries from x_k + k_j are also sorted.

PS I am looking for algorithmic / language agnostic ideas. Basically a C ++ tag in case this requires the use of some kind of smart caching strategy.

Edit:

@liori makes a good point below that finding a pair (j, k) for a given i is O (n) using an algorithm similar to what was done in the last iteration of this answer to the corresponding question . Here we are talking about IMO about whether it is possible to combine these many steps O (n) more efficiently than naively. For example, we can find a pair (j, k) for a given index i in time O (n). But is it necessary to consider again all the elements j '<= j and k' <= k as candidates for the next index i '= i + 1? Are these savings saved?

+4
3

:

i∈ {1,..., N}:

  • j=i-1, k=i+1.
  • j<1 k>N, .
  • d=(x_i - x_j) - (x_k - x_i)
  • d=0, .
  • d<0, j--.
  • d>0, k++.
  • 2.

, x_i , x_j ( x_i - x_j), x_k (x_k - x_i). , , .

+3

, "" , n O (n log n).

3SUM - , , . , , . , , - O (n log n) .

, , parallelism, 3SUM. , , , .

+4

& Omicron; (n 2). - . , , 0 1, :

typedef std::pair<int, int> xy;
typedef std::unordered_map<int, xy> sums;

template <int N>
xy func (const int (&a)[N]) {
    sums s(2*N*N);
    for (int lo = 0; lo < N-2; ++lo) {
        for (int hi = lo+2; hi < N; ++hi) {
            int ss = a[lo] + a[hi];
            if (ss % 2 == 0) s[ss] = xy(lo, hi);
        }
    }
    for (int i = 1; i < N-1; ++i) {
        if (s.find(2*a[i]) != s.end()) return s[2*a[i]];
    }
    return xy(0, 0);
}

: & Omicron; (n 2).

, , , , x i (x j, x k). , (x j, x k) x i. , , , , .

+2

All Articles