题解 | 构造C的歪,分三种情况进行逐一验证
构造C的歪
https://www.nowcoder.com/practice/56735b3fe2fc4ed5916f5427dc787156
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
// Write your code here
while ((line = await readline())) {
const [n, m] = line.split(" ").map(Number);
const ascArr = [n, m].sort((a, b) => a - b);
/**
* 分为三种情况
* 假设现有数字a和b,要找c
* 1. 数字c是最小的数,那么排序后就是 c a b,则等差中项为 a,所以 a = (c + b) / 2, 即c = 2*a - b
* 2. 数字c是中间的数,那么排序后就是 a c b,则等差中项为 c,所以 c = (a + b) / 2,题目要求得到一个整数
* 所以a + b的结果就要求是偶数,否则 c 不是偶数
* 3. 数字c是最大的数,那么排序后就是 a b c,则等差中项为 b,所以 b = (c + a) / 2, 即c = 2*b - a
*
* 没有说c不能等于a或者b,等差数列是允许有两个数字相同的,常数列,所以c可以等于a或者b
*/
// 这个方法只是得到了唯一性的数据
// 不像题目中给出的 3和2 可以得到1或者4
// 方法只能得到一种值,1或者4
function findCForArithmeticProgression(a, b) {
// 三种可能的c值
const candidates = [];
// 情况1:排序后为 [a, b, c],等差中项为 b
// 等差公式:b - a = c - b,所以 c = 2b - a
candidates.push(2 * b - a);
// 情况2:排序后为 [a, c, b],等差中项为 c
// 等差公式:c - a = b - c,所以 c = (a + b) / 2
if ((a + b) % 2 === 0) {
candidates.push((a + b) / 2);
}
// 情况3:排序后为 [c, a, b],等差中项为 a
// 等差公式:a - c = b - a,所以 c = 2a - b
candidates.push(2 * a - b);
// 将三种可能性的数据拿到逐一验证
for (const c of candidates) {
// 将三种情况的数据与现有的两个数字放在一起排序,如果形成等差数列,则返回
const sorted = [a, b, c].sort((x, y) => x - y);
if (sorted[1] - sorted[0] === sorted[2] - sorted[1]) {
return c;
}
}
// 兜底,如果上面的都没找到
return candidates[0];
}
const [a, b] = ascArr; // 结构出排序后的数字
console.log(findCForArithmeticProgression(a, b));
}
})();
#华为机试HJ42##华为机试##js解法##算法题#

