Algorithm to determine if array contains n…n+m?

前端 未结 30 3204
清酒与你
清酒与你 2020-11-28 01:45

I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview

30条回答
  •  孤街浪徒
    2020-11-28 01:51

    Oops! I got caught up in a duplicate question and did not see the already identical solutions here. And I thought I'd finally done something original! Here is a historical archive of when I was slightly more pleased:


    Well, I have no certainty if this algorithm satisfies all conditions. In fact, I haven't even validated that it works beyond a couple test cases I have tried. Even if my algorithm does have problems, hopefully my approach sparks some solutions.

    This algorithm, to my knowledge, works in constant memory and scans the array three times. Perhaps an added bonus is that it works for the full range of integers, if that wasn't part of the original problem.

    I am not much of a pseudo-code person, and I really think the code might simply make more sense than words. Here is an implementation I wrote in PHP. Take heed of the comments.

    function is_permutation($ints) {
    
      /* Gather some meta-data. These scans can
         be done simultaneously */
      $lowest = min($ints);
      $length = count($ints);
    
      $max_index = $length - 1;
    
      $sort_run_count = 0;
    
      /* I do not have any proof that running this sort twice
         will always completely sort the array (of course only
         intentionally happening if the array is a permutation) */
    
      while ($sort_run_count < 2) {
    
        for ($i = 0; $i < $length; ++$i) {
    
          $dest_index = $ints[$i] - $lowest;
    
          if ($i == $dest_index) {
            continue;
          }
    
          if ($dest_index > $max_index) {
            return false;
          }
    
          if ($ints[$i] == $ints[$dest_index]) {
            return false;
          }
    
          $temp = $ints[$dest_index];
          $ints[$dest_index] = $ints[$i];
          $ints[$i] = $temp;
    
        }
    
        ++$sort_run_count;
    
      }
    
      return true;
    
    }
    

提交回复
热议问题