zoukankan      html  css  js  c++  java
  • 0754. Reach a Number (M)

    Reach a Number (M)

    题目

    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出发,第n步可以向左或向右走n步,问最少需要几步走到指定值。

    思路

    target正负不影响,为方便取target绝对值。先求出k,使得sum=1+2+...+k恰好大于target,如果sum-target为偶数,说明在1~k这k步中,只要第(sum-target)/2这一步变为向左走,就能正好到达target;如果sum-target为奇数,说明还需要再走1步或2步,使(sum+k+1-target)为偶数或(sum+k+1+k+2-target)为偶数,这样也能在1~k+1或1~k+2中选一步向左走,使得正好走到target。


    代码实现

    Java

    class Solution {
        public int reachNumber(int target) {
            target = Math.abs(target);
            int step = 0, sum = 0;
            while (sum < target) {
                sum += ++step;
            }
            return (sum - target) % 2 == 0 ? step : step % 2 == 0 ? step + 1 : step + 2;
        }
    }
    
  • 相关阅读:
    Atlassian In Action-Jira之核心配置(二)
    mybatis的插入与批量插入的返回ID的原理
    Atlassian In Action-Jira之指导思想(一)
    Atlassian In Action
    如何进行软件技术管理?
    [simple-orm-mybaits]基于Mybatis的ORM封装介绍
    Java利用Mybatis进行数据权限控制
    给大家推荐一个Java学习和面试的GitHub项目
    立志
    一勤天下无难事
  • 原文地址:https://www.cnblogs.com/mapoos/p/14206173.html
Copyright © 2011-2022 走看看