私は最近仕事に応募し、要件はテストを完了してから面接することでした。テストのために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);