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

前端 未结 30 3206
清酒与你
清酒与你 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:55

    Here's a working solution in O(n)

    This is using the pseudocode suggested by Hazzen plus some of my own ideas. It works for negative numbers as well and doesn't require any sum-of-the-squares stuff.

    function testArray($nums, $n, $m) {
        // check the sum. PHP offers this array_sum() method, but it's
        // trivial to write your own. O(n) here.
        if (array_sum($nums) != ($m * ($m + 2 * $n - 1) / 2)) {
            return false;    // checksum failed.
        }
        for ($i = 0; $i < $m; ++$i) {
            // check if the number is in the proper range
            if ($nums[$i] < $n || $nums[$i] >= $n + $m) {
                return false;  // value out of range.
            }
    
            while (($shouldBe = $nums[$i] - $n) != $i) {
                if ($nums[$shouldBe] == $nums[$i]) {
                    return false;    // duplicate
                }
                $temp = $nums[$i];
                $nums[$i] = $nums[$shouldBe];
                $nums[$shouldBe] = $temp;
            }
        }
        return true;    // huzzah!
    }
    
    var_dump(testArray(array(1, 2, 3, 4, 5), 1, 5));  // true
    var_dump(testArray(array(5, 4, 3, 2, 1), 1, 5));  // true
    var_dump(testArray(array(6, 4, 3, 2, 0), 1, 5));  // false - out of range
    var_dump(testArray(array(5, 5, 3, 2, 1), 1, 5));  // false - checksum fail
    var_dump(testArray(array(5, 4, 3, 2, 5), 1, 5));  // false - dupe
    var_dump(testArray(array(-2, -1, 0, 1, 2), -2, 5)); // true
    

提交回复
热议问题