一道easy题,题目如下,不过是一道数学题,以后可能会用到相关的结论,所以记录下
【leetcode】754. Reach a Number解题报告
其实就是相当于

[ ]1[ ]2[ ]3[ ]...[ ]n = target 

让你在括号里填上±符号,使得n最小
思路:

  • 如果不按照某个方向一直走,那么走到第N步的时候,走过的距离为1+2+3+..+N
  • 如果其中第j步朝着反方向走,那么走过的距离就是在原来朝着某个方向走距离的基础上减去2*j
  • 所以一直target 方向走,如果超过了,继续向前走直到走的距离和-target 的值为偶数就行了,因为这个多出的偶数值肯定是可以被前面n步中的某一步以向反方向走的形式抵消
class Solution:
    def reachNumber(self, target):
        """
        :type target: int
        :rtype: int
        """
        target =abs(target)
        step = 0
        sum =0
        while(sum <target):
            step+=1
            sum +=step
        while((sum -target)%2!=0):
            step +=1
            sum +=step
        return step

相关文章: