[英]What is wrong my implementing of binary search algorithm
I am trying to fix the one task from Coursera regarding Binary Search Algorithm.我正在尝试解决 Coursera 关于二进制搜索算法的一项任务。 When I am testing my solution it works well.当我测试我的解决方案时,它运行良好。 But the Autograder of Coursera is not accepting my solution and throwing that .但是 Coursera 的 Autograder 不接受我的解决方案并抛出它。 What am I missing ?我错过了什么?
Failed case #17/36: Wrong answer失败案例#17/36:错误答案
(Time used: 0.06/5.00, memory used: 46239744/536870912.) (使用时间:0.06/5.00,使用内存:46239744/536870912。)
The task Input Format -- The first line of the input contains an integer n and a sequence a0 < a1 < ... < an−1 of n pairwise distinct positive integers in increasing order.任务输入格式——输入的第一行包含一个整数 n 和一个序列 a0 < a1 < ... < an−1,其中 n 对不同的正整数按递增顺序排列。 The next line contains an integer k and k positive integers b0,b1,...,bk−1.下一行包含一个整数 k 和 k 个正整数 b0,b1,...,bk−1。
Constraints -- 1 ≤ n,k ≤ 10^4;约束——1≤n,k≤10^4; 1 ≤ a[i] ≤ 10^9 for all 0 ≤ i < n; 1 ≤ a[i] ≤ 10^9 对于所有 0 ≤ i < n; 1 ≤ b[]j ≤ 10^9 for all 0 ≤ j < k; 1 ≤ b[]j ≤ 10^9 对于所有 0 ≤ j < k;
Output Format -- For all i from 0 to k−1, output an index 0 ≤ j ≤ n−1 such that aj = bi or −1 if there is no such index.输出格式——对于从 0 到 k−1 的所有 i,输出一个索引 0 ≤ j ≤ n−1 使得 aj = bi 或 -1 如果没有这样的索引。
Sample 1.样品 1。
Input:输入:
5 5
1 5 8 12 13 1 5 8 12 13
5 5
8 1 23 1 11 8 1 23 1 11
Output:输出:
2 0 -1 0 -1 2 0 -1 0 -1
In this sample, we are given an increasing sequence 𝑎0 = 1, 𝑎1 = 5, 𝑎2 = 8, 𝑎3 = 12, 𝑎4 = 13 of length five and five keys to search: 8, 1, 23, 1, 11. We see that 𝑎2 = 8 and 𝑎0 = 1, but the keys 23 and 11 do not appear in the sequence 𝑎.在这个示例中,我们得到一个递增序列 𝑎0 = 1,𝑎1 = 5,𝑎2 = 8,𝑎3 = 12,𝑎4 = 13,长度为 5 和要搜索的五个键:8、1、23、1、11。我们看到𝑎2 = 8 和 𝑎0 = 1,但是键 23 和 11 没有出现在序列 𝑎 中。 For this reason, we output a sequence 2, 0,−1, 0,−1.出于这个原因,我们输出一个序列 2, 0,-1, 0,-1。
My solution我的解决方案
function implemenetBinary(firstArray, secondArray) {
var locationArray = [];
for (let i = 0; i < secondArray.length; i++) {
let value = secondArray[i];
locationArray[i] = binarySearch(firstArray, value);
}
console.log(...locationArray);
return locationArray;
}
function binarySearch(arr, val) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === val) {
return mid;
}
if (val < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
var readline = require("readline");
process.stdin.setEncoding("utf8");
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
rl.on("line", readLine);
let inputLines = [];
function readLine(line) {
inputLines.push(line.toString().split(" ").map(Number));
if (inputLines.length == 4) {
implemenetBinary(inputLines[1], inputLines[3]);
}
}
Your binary search is fine.你的二分搜索很好。
Your input processing is broken on the empty lines you can get when n
or k
are 0.当n
或k
为 0 时,您的输入处理在您可以获得的空行上中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.