-1

我最近申请了一份工作,要求是完成一个测试,然后面试 2 个问题用于测试,非常简单,我成功完成了,但我仍然被告知我没有通过测试,因为脚本花费超过18秒完成执行。这是我不明白我还能做些什么来让它快速的程序。虽然我没有通过测试,但仍然想知道我还能做什么?程序语言是 PHP,我必须使用命令行输入

这是问题:

 K Difference
Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]

Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.

Sample Input #00:
5 2
1 5 3 4 2

Sample Output #00:3
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793 
Sample Output #01:
0
Note: Java/C# code should be in a class named "Solution"
Read input from STDIN and write output to STDOUT.

这就是解决方案

$fr = fopen("php://stdin", "r");
$fw = fopen("php://stdout", "w");

fscanf($fr, "%d", $total_nums);
fscanf($fr, "%d", $diff);

$ary_nums = array();
for ($i = 0; $i < $total_nums; $i++) {
    fscanf($fr, "%d", $ary_nums[$i]);
}

$count = 0;
sort($ary_nums);
for ($i = $total_nums - 1; $i > 0; $i--) {
    for ($j = $i - 1; $j >= 0; $j--) {
        if ($ary_nums[$i] - $ary_nums[$j] == $diff) {
            $count++;
            $j = 0;
        }
    }
}
fprintf($fw, "%d", $count);
4

2 回答 2

3

您的算法的运行时间为 O(N^2),大约为 10^5 * 10^5 = 10^10。通过一些基本的观察,它可以减少到 O(NlgN),大约只有 10^5*16 = 1.6*10^6。

算法:

  1. 对数组 ary_nums 进行排序。
  2. 对于数组的每个第 i 个整数,进行二进制搜索以查找 ary_nums[i]-K, 是否存在于数组中。如果存在增加结果,则跳过第 i 个整数。

排序($ary_nums);

for ($i = $total_nums - 1; $i > 0; $i--) {

        $hi  = $i-1;
        $low = 0;
        while($hi>=$low){
            $mid = ($hi+$low)/2;
            if($ary_nums[$mid]==$ary_nums[$i]-$diff){
                $count++;
                break;
            }
            if($ary_nums[$mid]<$ary_nums[$i]-$diff){
                 $low = $mid+1;
            }
            else{
                 $hi  = $mid-1;
            }
        }
    }
}
于 2013-07-25T05:17:17.307 回答
0

我的技术面试也有同样的问题。我想知道我们是不是在同一家公司面试。:)

无论如何,这是我想出的答案(面试后):

// Insert code to get the input here

$count = 0;
sort ($arr);

for ($i = 0, $max = $N - 1; $i < $max; $i++)
{
   $lower_limit = $i + 1;
   $upper_limit = $max;

   while ($lower_limit <= $upper_limit)
   {
      $midpoint = ceil (($lower_limit + $upper_limit) / 2);
      $diff = $arr[$midpoint] - $arr[$i];

      if ($diff == $K)
      {
         // Found it. Increment the count and break the inner loop.
         $count++;
         $lower_limit = $upper_limit + 1;
      }
      elseif ($diff < $K)
      {
         // Search to the right of midpoint
         $lower_limit = $midpoint + 1;
      }
      else
      {
         // Search to the left of midpoint
         $upper_limit = $midpoint - 1;
      }
   }
}

@Fallen:您的代码因以下输入而失败:

Enter the numbers N and K: 10 3
Enter numbers for the set: 1 2 3 4 5 6 7 8 9 10
Result: 6 

我认为这与您的计算有关$mid(不考虑奇数)

于 2013-08-01T16:20:33.263 回答