Possible PHP solution, what do you think?


  • 0
    P

    I wouldn't know how to define space, is that O(N)?

    $sample = [2,3,4,4,4];
    
    function process_sample_into_hashmap( $sample ) {
      $indexes = [];
      for( $iter = 0;$iter < count( $sample ); $iter++ ) {
        $number = $sample[$iter];
        if ( ! isset( $indexes[$number] ) ) {
          $indexes[$number] = [];
        }
        $indexes[$number][] = $iter;
      }
      return $indexes;
    }
    
    function get_random_index( $number, $indexes ) {
      if ( isset( $indexes[$number] ) ) {
        $possible_indexes = $indexes[$number];
        $rand = random_int( 1, count( $possible_indexes ) ) - 1;
        return $possible_indexes[$rand];
      }
    }
    $indexes = process_sample_into_hashmap( $sample );
    echo get_random_index( 4, $indexes );
    `

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.