• 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;
        }
    }
    
  • 相关阅读:
    马云演讲:给自己一个梦想,给自己一个承诺,给自己一个坚持!
    转:如何成为一个伟大的开发者
    数据挖掘之七种常用的方法
    windows命令行
    100万亿意味着什么?
    ubuntu环境配置
    Ubuntu runlevel修改
    Ubuntu 用户及组管理
    Git学习笔记
    Git详解之三 Git分支
  • 原文地址:https://www.cnblogs.com/mapoos/p/14206173.html
Copyright © 2020-2023  润新知