File tree Expand file tree Collapse file tree 3 files changed +117
-0
lines changed
2485-Find the Pivot Integer Expand file tree Collapse file tree 3 files changed +117
-0
lines changed Original file line number Diff line number Diff line change 1+ # 2485. Find the Pivot Integer
2+
3+ Given a positive integer ` n ` , find the pivot integer ` x ` such that:
4+
5+ - The sum of all elements between ` 1 ` and ` x ` inclusively equals the sum of all elements between ` x ` and ` n ` inclusively.
6+
7+ Return the pivot integer ` x ` .
8+ If no such integer exists, return ` -1 ` .
9+ It is guaranteed that there will be at most one pivot index for the given input.
10+
11+ ** Constraints:**
12+
13+ - ` 1 <= n <= 1000 `
14+
15+ # 基礎思路
16+
17+ 本題要求尋找一個整數 ` x ` ,使得:
18+
19+ $$
20+ 1 + 2 + \cdots + x = x + (x+1) + \cdots + n
21+ $$
22+
23+ 這是一個兩側求和相等的問題,但若直接逐一求和會造成 $O(n)$ 的成本。
24+ 更好的方式是利用** 等差級數的性質** 進行化簡。
25+
26+ 觀察可得:
27+
28+ * 左側求和為
29+
30+ $$
31+ S_L = \frac{x(x+1)}{2}
32+ $$
33+
34+ * 右側求和為
35+
36+ $$
37+ S_R = \frac{n(n+1)}{2} - \frac{(x-1)x}{2}
38+ $$
39+
40+ 令兩側相等並化簡後會得到:
41+
42+ $$
43+ x^2 = \frac{n(n+1)}{2}
44+ $$
45+
46+ 因此:
47+
48+ - 若總和 $\frac{n(n+1)}{2}$ 是** 完全平方數** ,答案即為 ` x = √(總和) ` 。
49+ - 否則不存在滿足條件的 pivot integer。
50+
51+ 此方法可在常數時間 $O(1)$ 內完成。
52+
53+ ## 解題步驟
54+
55+ ### Step 1:計算 1 到 n 的總和
56+
57+ 使用等差級數公式計算總和,作為後續檢查 pivot 是否可能存在的基礎。
58+
59+ ``` typescript
60+ // 使用等差級數公式計算 1 到 n 的總和
61+ const totalSumFromOneToN = (n * (n + 1 )) / 2 ;
62+ ```
63+
64+ ### Step 2:計算總和的平方根候選值
65+
66+ 若 pivot integer 存在,其值必須是總和的平方根,因此先取整數平方根。
67+
68+ ``` typescript
69+ // 計算總和的整數平方根作為 pivot 候選
70+ const candidatePivot = Math .floor (Math .sqrt (totalSumFromOneToN ));
71+ ```
72+
73+ ### Step 3:檢查是否為完全平方數並返回結果
74+
75+ 若平方根平方後等於總和,代表 pivot 存在並返回;否則回傳 -1。
76+
77+ ``` typescript
78+ // 若平方後等於總和,表示為完全平方數
79+ if (candidatePivot * candidatePivot === totalSumFromOneToN ) {
80+ return candidatePivot ;
81+ }
82+
83+ // 若不符合,則不存在 pivot integer
84+ return - 1 ;
85+ ```
86+
87+ ## 時間複雜度
88+
89+ - 所有計算皆為常數運算。
90+ - 總時間複雜度為 $O(1)$。
91+
92+ > $O(1)$
93+
94+ ## 空間複雜度
95+
96+ - 僅使用常數額外變數。
97+ - 總空間複雜度為 $O(1)$。
98+
99+ > $O(1)$
Original file line number Diff line number Diff line change 1+ function pivotInteger ( n : number ) : number {
2+ // Compute the total sum from 1 to n using the arithmetic series formula
3+ const totalSumFromOneToN = ( n * ( n + 1 ) ) / 2 ;
4+
5+ // Compute the integer square root candidate for the total sum
6+ const candidatePivot = Math . floor ( Math . sqrt ( totalSumFromOneToN ) ) ;
7+
8+ // Verify if the candidatePivot squared equals the total sum (perfect square check)
9+ if ( candidatePivot * candidatePivot === totalSumFromOneToN ) {
10+ return candidatePivot ;
11+ }
12+
13+ // If no integer pivot satisfies the condition, return -1
14+ return - 1 ;
15+ }
Original file line number Diff line number Diff line change 1+ function pivotInteger ( n : number ) : number {
2+
3+ }
You can’t perform that action at this time.
0 commit comments