Python3解leetcode Reach a Number
问题描述:
You are standing at position 0 on an infinite number line. There is a goal at position target.
On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.
Return the minimum number of steps required to reach the destination.
Example 1:
Input: target = 3
Output: 2
Explanation:
On the first move we step from 0 to 1.
On the second step we step from 1 to 3.
Example 2:
Input: target = 2
Output: 3
Explanation:
On the first move we step from 0 to 1.
On the second move we step from 1 to -1.
On the third move we step from -1 to 2.
Note:
targetwill be a non-zero integer in the range[-10^9, 10^9].
思路:
这道题让我们从起点0开始,每次可以向数轴的左右两个方向中的任意一个走,第一步走距离1,第二步走距离2,以此类推,第n步走距离n,然后给了我们一个目标值 target,问我们最少用多少步可以到达这个值。
最开始想的是用贪婪算法来做,就是如果加上距离大于目标值的话,就减去这个距离,到是当目标值是4的话,贪婪算法会fail。
一般贪婪算法不行的话,很自然的就会想想能否用DP来做,但这道题感觉很难很难重现为子问题,因为每一步走的步数都不一样,这个步数又跟最小步数息息相关,所以很难写出状态转移方程啊,只得放弃。
其实这道题的正确解法用到了些数学知识,还有一些小 trick,首先来说说小 trick,第一个 trick 是到达 target 和 -target 的步数相同,因为数轴是对称的,只要将到达 target 的每步的距离都取反,就能到达 -target。下面来说第二个 trick,这个是解题的关键,比如说目标值是4,那么如果我们一直累加步数,直到其正好大于等于target时,有:
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
第三步加上3,得到了6,超过了目标值4,超过了的距离为2,是偶数,那么实际上我们只要将加上距离为1的时候,不加1,而是加 -1,那么此时累加和就损失了2,那么正好能到目标值4,如下:
0 - 1 = -1
-1 + 2 = 1
1 + 3 = 4
那么,我们的第二个 trick 就是,当超过目标值的差值d为偶数时,只要将第 d/2 步的距离取反,就能得到目标值,此时的步数即为到达目标值的步数。
那么,如果d为奇数时,且当前为第n步,那么我们看下一步 n+1 的奇偶,如果 n+1 为奇数,那么加上 n+1 再做差,得到的差值就为偶数了,问题解决,如果 n+1 为偶数,那么还得加上 n+2 这个奇数,才能让差值为偶数,这样就多加了两步。
那么,我们的第三个 trick 就是,可以利用求和公式,直接求出当前的n和对应的sums,在当前n和sums的基础上进行判断,这样可以大大减少前期累加的时间,提高效率
代码:
class Solution:
def reachNumber(self, target: int) -> int:
target , sums = abs(target) , 0
n = int(math.sqrt(2*target))
sums = ((n + 1)*n)/2 while True:
if sums > target:
if (sums - target) % 2 :
if (n + 1) % 2:
return n + 1
else:
return n + 2
else:
return n
elif sums == target:
return n
n += 1
sums += n
Python3解leetcode Reach a Number的更多相关文章
- Python3解leetcode Number of Boomerangs
问题描述: Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple ...
- Python3解leetcode Single Number
问题描述: Given a non-empty array of integers, every element appears twice except for one. Find that sin ...
- [LeetCode] Reach a Number 达到一个数字
You are standing at position 0 on an infinite number line. There is a goal at position target. On ea ...
- Python3解leetcode N-ary Tree Level Order Traversal
问题描述: Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to ...
- 详解LeetCode 137. Single Number II
Given an array of integers, every element appears three times except for one, which appears exactly ...
- Python3解leetcode Maximum SubarrayClimbing Stairs
问题: You are climbing a stair case. It takes n steps to reach to the top. Each time you can either cl ...
- Python3解leetcode Maximum Subarray
问题描述: Given an integer array nums, find the contiguous subarray (containing at least one number) whi ...
- Python3解leetcode Min Cost Climbing Stairs
问题描述: On a staircase, the i-th step has some non-negative cost cost[i]assigned (0 indexed). Once you ...
- Python3解leetcode Count Binary Substrings
问题描述: Give a string s, count the number of non-empty (contiguous) substrings that have the same numb ...
随机推荐
- 013-Spring Boot web【二】静态资源、Servlet、Filter、listenter
一.静态资源 1.1.webapp默认支持静态资源 在src/main/webapp下建立user.html默认支持访问 1.2.默认内置静态资源目录.可被直接访问 查看包:spring-boot-a ...
- dataframe指定位置插入行
1 loc( ) 函数可以定位行后,并直接赋值插入. 如下可见loc函数对直接改变原来行的值 df = pd.DataFrame({ '动物' : ['狗','猫','兔'], '数量' : [ 3, ...
- robot framework :List Variables-List变量及其用法
[转自:https://blog.csdn.net/yezibang/article/details/52692342] 这一讲我们重点来介绍List Variables-List变量及其用法. 一. ...
- Centos7上安装Nginx两种方法
源码编译安装 http://nginx.org/en/download.html 到官网下载,然后用XFTP上传到root目录 把文件解压出来 tar -zxvf nginx-1.16.0.tar.g ...
- js模块化编程之CommonJS和AMD/CMD!
有了模块,我们就可以更方便地使用别人的代码,想要什么功能,就加载什么模块. 但是,这样做有一个前提,那就是大家必须以同样的方式编写模块,否则你有你的写法,我有我的写法,岂不是乱了套! 于是下面三个模块 ...
- tbox新增stackless协程支持
tbox之前提供的stackfull协程库,虽然切换效率已经非常高了,但是由于每个协程都需要维护一个独立的堆栈, 内存空间利用率不是很高,在并发量非常大的时候,内存使用量会相当大. 之前考虑过采用st ...
- WPF资源字典的使用
1.在解决方案中添加资源字典:鼠标右键——添加——资源字典 2.在资源字典中写入你需要的样式,我这里简单的写了一个窗体的边框样式 3.在App.xaml中加入刚刚新建的资源字典就好了
- JAVA的学习
怎么说呢,我已经接触JAVA已经两周了,个人感觉还是不懂,哈哈,JAVA是一门编程语言,是大多数开发者较为习惯的编程模式,我感觉相对比C语言来说可能简单学点,可能是我先接触C语言把,或许因人而异把,在 ...
- 多线程07-Monitor.TryEnter
); Console.WriteLine())) { Console.WriteLine ...
- mybatis加载配置文件详解
spring整合Mybatis后,SqlSessionFactory的创建由spring进行了代理,以下是SqlSessionFactory创建的流程 SqlSessionFactoryBean: p ...