CC150 20.5

20.5 You have a large text file containing words. Given any two words, find the shortest distance (in terms of number of words) between them in the file. Can you make the searching operation in O(1) time? What about the space complexity for your solution?

// Iterate the file
// each word would have an array containing positions.
// E.g.
// word 'A': [1, 3, 5, 8];
// word 'B': [6 , 10, 499];
// Then find the a pair of [a, b], which |a-b| is min.

// preparation, building map.
// ...


// Assume a and b are not null.
// All elements are > 1.
// No duplicated elements across a & b.

// Say book contains m A, and n B.
// Would be O(m + n) => O(n)
int[] shortestDis(int[] a, int[] b)
{
  int cura = 0;
  int curb = 0;
  
  int minA = -1;
  int minB = -1;
  int minDis = MAX;
  for (cura < a.length && curb < b.length)
  {
    int dis = Math.abs(a[cura] - b[curb]);
    if (dis == 1) // Find
    {
      return [cura, curb];
    }
    
    if (dis < minDis)
    {
      minA = cura;
      minB = curb;
      minDis = dis;
    }
    
    if (a[cura] < [curb])
    {
      cura ++;
    }
    else // == is not possible.
    {
      curb ++;
    }
    
    return [minA, minB];
  }
}

// To make it real O(1).
// A map, key is pair of word, value is distance.

你可能感兴趣的:(interview)