Tricky Google interview question

前端 未结 21 1715
花落未央
花落未央 2020-12-22 15:39

A friend of mine is interviewing for a job. One of the interview questions got me thinking, just wanted some feedback.

There are 2 non-negative integers: i and j. Gi

21条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-22 16:11

    You know that log_2(5)=2.32. From this we note that 2^2 < 5 and 2^3 > 5.

    Now look a matrix of possible answers:

    j/i  0   1   2   3   4   5
     0   1   2   4   8  16  32
     1   5  10  20  40  80 160 
     2  25  50 100 200 400 800
     3 125 250 500 ...
    

    Now, for this example, choose the numbers in order. There ordering would be:

    j/i  0   1   2   3   4   5
     0   1   2   3   5   7  10
     1   4   6   8  11  14  18
     2   9  12  15  19  23  27
     3  16  20  24...
    

    Note that every row starts 2 columns behind the row starting it. For instance, i=0 j=1 comes directly after i=2 j=0.

    An algorithm we can derive from this pattern is therefore (assume j>i):

    int i = 2;
    int j = 5;
    int k;
    int m;
    
    int space = (int)(log((float)j)/log((float)i));
    for(k = 0; k < space*10; k++)
    {
        for(m = 0; m < 10; m++)
        {
            int newi = k-space*m;
            if(newi < 0)
                break;
            else if(newi > 10)
                continue;
            int result = pow((float)i,newi) * pow((float)j,m);
            printf("%d^%d * %d^%d = %d\n", i, newi, j, m, result);
        }
    }   
    

    NOTE: The code here caps the values of the exponents of i and j to be less than 10. You could easily extend this algorithm to fit into any other arbitrary bounds.

    NOTE: The running time for this algorithm is O(n) for the first n answers.

    NOTE: The space complexity for this algorithm is O(1)

提交回复
热议问题