Get rid of ugly if statements

后端 未结 25 2241
借酒劲吻你
借酒劲吻你 2020-12-02 05:59

I have this ugly code:

if ( v > 10 ) size = 6;
if ( v > 22 ) size = 5;
if ( v > 51 ) size = 4;
if ( v > 68 ) size = 3;
if ( v > 117 ) size = 2         


        
25条回答
  •  余生分开走
    2020-12-02 06:16

    If you really want the fastest big-O complexity time solution for this particular answer this one is constant lookup.

    final int minBoundary = 10;
    final int maxBoundary = 145;
    final int maxSize = 6;
    Vector index = new Vector(maxBoundary);
        // run through once and set the values in your index
    

    subsequently

    if( v > minBoundary )
    {
       size = (v > maxBoundary ) ? maxSize : index[v];
    }
    

    What we are doing here is marking all the possible results of v within the range and where they fall, and then we only need to test for boundary conditions.

    The issue with this is that it uses more memory and of course if maxBoundary is a lot bigger it will be very space inefficient (as well as take a longer time to initialise).

    This may sometimes be the best solution for the situation.

提交回复
热议问题