前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >754. Reach a Number

754. Reach a Number

作者头像
用户1147447
发布2019-05-26 00:16:30
2860
发布2019-05-26 00:16:30
举报
文章被收录于专栏:机器学习入门机器学习入门

LWC 65: 754. Reach a Number

传送门:754. Reach a Number

Problem

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:

  • target will be a non-zero integer in the range [-10^9, 10^9].

思路: 本人没有特别好的思路,只能多举几个例子发现模式。例如,从0开始,第一步能够产生{+1, -1}, 第二步能够产生{+1, -1, +3, -3},我们枚举到第六步,有:

代码语言:javascript
复制
0
1
1 3
0 2 4 6
0 2 4 6 8 10
1 3 5 7 9 11 13 15
1 3 5 7 9 11 13 15 17 19 21

注意:每一个数字代表的是绝对值,也就是说正负都能取到。观察最后一列数字,有:

代码语言:javascript
复制
0
1
3
6
10
15
21

对应的有:
1 = 0 + 1
3 = 0 + 1 + 2 = 3
6 = 0 + 1 + 2 + 3 = 6
...
21 = 0 + 1 + 2 + 3 + 4 + 5 + 6 = 21

所以首先我们要确定step,最后一个数用sum来表示,如果target > sum说明还没加够,必须让sum >= target, 但发现每两行是同奇或同偶,所以如果sum - target为偶数,说明在此行,直接输出,如果为奇数,那么step必须还得往后数,此时,step为偶数时 + 1, step为奇数时 + 2.

Java版本:

代码语言:javascript
复制
    public int reachNumber(int target) {
        target = Math.abs(target);
        int sum = 0;
        int n   = 0;
        while (sum < target){
            n ++;
            sum += n;
        }
        if (sum == target) return n;
        int res = sum - target;
        if ((res & 1) == 0) {
            return n;
        }
        else {
            return n + ((n & 1) == 0 ? 1 : 2);
        }
    }

Python版本:

代码语言:javascript
复制
class Solution(object):
    def reachNumber(self, target):
        """
        :type target: int
        :rtype: int
        """
        t = abs(target)
        n = 0
        sum = 0
        while (t > sum):
            n += 1
            sum += n
        if t == sum: return n
        rem = sum - target
        if (rem % 2) == 0: return n
        else:
            return n + 1 if (n % 2) == 0 else n + 2
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年01月02日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 65: 754. Reach a Number
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档