Monday, October 20, 2014

Changes 10/20/14

Title:

  •   public int firstDuplicate( int[] a )
      {
        int y = -1;
        for ( int i = 0 ; i < a.length - 1 && y == -1 ; i++ )
        {
          if ( a[ i ] == a[ i + 1 ] )
            y = i;
        }
        return y;
      }
    
  • I've never seen an exit condition within the boolean of a for loop, which threw me off for one of the quiz questions for eimacs.
  • This function could be simplified by removing the y variable and simply returning i when a[i] is found to equal a[i+1]
  • I also was reminded that big O notation refers to asymptotic behavior, so a function with points (0,0), (1,1) (2,4) and (3,9) could still be O(n), because big O deals with behavior of large values for n

1 comment:

  1. Actually, Alex, there is *always* an exit condition in a for loop, or you would have an infinite loop. What is new to you is to have two unrelated exit conditions, with one unrelated to the loop counter, which is what you are accustomed to.

    Anyway, it is not an uncommon idiom, so it is good you are seeing it.

    ReplyDelete