Блог пользователя hollow

Автор hollow, 14 лет назад, По-английски

In many problems i see the tag "two pointers". I assume its a technique. I dont have an idea on it can anybody give any type of reference. Thanks.

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

»
14 лет назад, скрыть # |
Rev. 5  
Проголосовать: нравится +10 Проголосовать: не нравится

I will try to describe this method on example of a problem.
Given two arrays (A and B) sorted in ascending order, and an integer x. we need to find i and j, such that a[i] + b[j] is equal to X.
i and j our pointers, at first step i is points to the first element of a, and j points to the last element of b.

i = 0; j = b.size() - 1;

move first pointer one by one through the array a, and correct position of the second pointer if needed

while (i < a.size())
{
   while(a[i] + b[j] > X && j > 0) j--;
   if (a[i] + b[j] == X) writeAnswer(i, j);
   i++;
}

Also, there was the same question in Russian, maybe it can helps. link to google-translated version
http://mirror.codeforces.com/blog/entry/4136

»
7 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

If array elements are not distinct, the worst case is when all elements of both arrays are equal and the sum we are looking for is a[0] + b[0]. In this case all n2 pairs of indices form the needed summation, thus the best approach is an O(n2) brute force, so an O(n) solution will not work.

  • »
    »
    7 лет назад, скрыть # ^ |
     
    Проголосовать: нравится +1 Проголосовать: не нравится

    If you need the indices of all pairs, you may have O(n^2) results, so a O(n) is not possible, but if you need just how many index pairs there are, it's still solveable in O(n), just count how many there equal there are of a and b, and result is equalA*equalB.