Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (史萊哲林的優等生)時間1年前 (2024/03/13 11:52), 1年前編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串43/1548 (看更多)
※ 引述《Rushia (みけねこ的鼻屎)》之銘言: : https://leetcode.com/problems/find-the-pivot-integer : 2485. Find the Pivot Integer : 給定一個數字n,找出一個介於1~n的數字k滿足 1+2+...+k = k+(k+1)+(k+2)+...+n,如 : 果不存在返回-1。 : 思路: : 1.先求1~n的和 : 2.再遍歷一次1~n把pivot放進去判斷 我數學很爛 所以先求全數字和 然後for i = 1 to n 因為題目是 a+b+c = c+d+e 會有一個c位重複 所以每次迴圈 1. 先給left_sum加i 2. 比較left_sum跟right_sum 一樣就return i; 3. 再給right_sum減i 跑完找不到c就是-1 Code: impl Solution { pub fn pivot_integer(n: i32) -> i32 { if n <= 1 { return n; } let mut right_sum = n * (n + 1) / 2; let mut left_sum = 0; for i in 1..right_sum { left_sum += i; if right_sum == left_sum { return i; } right_sum -= i; } -1 } } 第二種數學解別人的解法: impl Solution { pub fn pivot_integer(n: i32) -> i32 { let p = ((n * (n + 1) / 2) as f64).sqrt(); if p == p.floor() { p as i32 } else { -1 } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.143.172 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1710301975.A.DD4.html ※ 編輯: yam276 (60.248.143.172 臺灣), 03/13/2024 11:56:02

03/13 12:17, 1年前 , 1F
大師
03/13 12:17, 1F
文章代碼(AID): #1byICNtK (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1byICNtK (Marginalman)