-
Notifications
You must be signed in to change notification settings - Fork 2
/
2485.找出中枢整数.html
83 lines (71 loc) · 2.2 KB
/
2485.找出中枢整数.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>2485.找出中枢整数</title>
</head>
<body>
<script>
// https://leetcode.cn/problems/find-the-pivot-integer/
// 给你一个正整数 n ,找出满足下述条件的 中枢整数 x :
//
// 提示:
// 1 和 x 之间的所有元素之和等于 x 和 n 之间所有元素之和。
// 返回中枢整数 x 。如果不存在中枢整数,则返回 -1 。题目保证对于给定的输入,至多存在一个中枢整数。
//
// 提示:
// 1 <= n <= 1000
/**
* @param {number} n
* @return {number}
*/
var pivotInteger = function (n) {};
// --- answer-1 ---
// 求和 前缀和 后缀和
var pivotInteger = function (n = 1) {
if (n === 1) return 1;
const pre = [];
const apd = [];
let sum1 = 0;
let sum2 = 0;
for (let i = 1; i <= n; i++) {
sum1 += i;
sum2 += n - i + 1;
pre.push(sum1);
apd[n - i] = sum2;
}
for (let i = 0; i < n; i++) {
if (pre[i] === apd[i]) {
return i + 1;
}
}
return -1;
};
// --- answer-1 ---
// --- answer-2 ---
// 设中枢整数位x
// 根据等差数列求和公式
// (1+x)*x/2 = (x+n)*(n-x+1)
// x = sqrt(n*(n+1)/2)
var pivotInteger = function (n) {
const res = Math.sqrt(((n + 1) * n) / 2);
return Number.isInteger(res) ? res : -1;
};
// --- answer-2 ---
var n = 8;
var result = 6;
// 解释:6 是中枢整数,因为 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21 。
var n = 1;
var result = 1;
// 解释:1 是中枢整数,因为 1 = 1 。
var n = 4;
var result = -1;
// 解释:可以证明不存在满足题目要求的整数。
console.log('n = ', n);
console.log('result = ', result);
console.log('pivotInteger = ', pivotInteger(n));
</script>
</body>
</html>