classSolution: defpivotInteger(self, n: int) -> int: x = int(n/2) flag = 0 num_table = [t for t inrange(1,n+1)] x_record = [] while x<n and x >= 0and x notin x_record: x_record.append(x) a_part , b_part = sum(num_table[:x+1]) , sum(num_table[x:]) if a_part == b_part: flag = 1 break if a_part < b_part:x=x+1 if a_part > b_part:x=x-1 return x+1if flag else -1
數學法
這題其實可以用數學的方式解,因為 1 到 n 的總和是可以用公式算出來的,所以只要把公式帶入,就可以得到答案。
classSolution: defpivotInteger(self, n: int) -> int: ''' x=( n(n+1)/2 )**0.5 n*(n+1)//2 must be a squared number 8*(8+1)//2=36 1*(1+1)//2=1 ''' tar=n*(n+1)//2 r=int(tar**0.5) return r if r*r==tar else -1