Skip to content

Instantly share code, notes, and snippets.

@XUJiahua
Created October 22, 2020 02:11
Show Gist options
  • Save XUJiahua/30f400d301ad5a953aac0b6e14fe7da6 to your computer and use it in GitHub Desktop.
Save XUJiahua/30f400d301ad5a953aac0b6e14fe7da6 to your computer and use it in GitHub Desktop.
find bugs
/*
输入一个数字数组,找出数组的中位数
找出其中的bug
*/
function findMedian(arr) {
arr.sort();
mid = arr.length / 2;
if (arr.length % 2 === 1) {
return arr[mid];
} else {
return (arr[mid] + arr[mid - 1]) / 2;
}
}
/*
题解
*/
function findMedianV2(arr) {
// 1. 边界条件处理,空数组不存在中位数
// 能看到边界问题的,就算通过,返回什么靠约定,没有标准答案
if (arr.length === 0) {
return null;
}
// 2. JavaScript默认使用字典序(alphanumeric)来排序。因此,[1,2,5,10].sort()的结果是[1, 10, 2, 5]。
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
// 指定排序策略
arr.sort((a, b) => a - b);
// 3. js里,所有的数都是浮点型,所以用 num1/num2 得出的数是浮点数,而非整数
// 向下取整
mid = Math.floor(arr.length / 2);
if (arr.length % 2 === 1) {
return arr[mid];
} else {
return (arr[mid] + arr[mid - 1]) / 2;
}
}
/*
测试用例
*/
function unitTest(f) {
testcases = [
[], null,
[1, 2, 3], 2,
[1, 2, 3, 4], 2.5,
[1, 2, 3, 10, 11], 3,
[1, 2, 3, 10, 11, 12], 6.5,
[90, 100, 78, 89, 67], 89
];
for (i = 0; i < testcases.length / 2; i++) {
input = testcases[2 * i];
expected = testcases[2 * i + 1];
actual = f(input);
console.assert(actual === expected, {
"input array": input,
"expected": expected,
"actual": actual,
});
}
}
unitTest(findMedian);
unitTest(findMedianV2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment