754. 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:
target will be a non-zero integer in the range [-10^9, 10^9].

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reach-a-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

1. target和-target的结果是一样的,所以我们只要求出target的绝对值的结果就好了。
2. 按照步数累加,假设target是8,我们先把步数累加到刚好大于等8
第一步:0 + 1 = 1
第二步:1 + 2 = 3
第三步:3 + 3 = 6
第四步:6 + 4 = 10
目标是8,现在算出来是10,那么相差2,这样子的话,那就要把第一步,变成减号,那么就造了一个2的落差了:
第一步:0 - 1 = -1
第二步:-1 + 2 = 1
第三步:1 + 3 = 4
第四步:4 + 4 = 8
这么看,就是说,先把数字累加到大约等于target,然后计算出差值diff,如果diff是偶数,那么直接把第diff/2步取反就好了。也就是说,8和10的步数是一样的。

现在我们看奇数的场景:如果现在target是9,是奇数,那么就只能往下走一步:
第五步:10 + 5 = 15
看15和9的差值是偶数,那么9和15的步数就是一样的,即target = 9,那么ans = 5.所以,如果当前找到的刚好超过的target的数字num,步数是n,但是差值是奇数,而且下一个要加的数字是奇数,那么只要往下走一步就能满足了,即答案是n + 1.

那么如果往下走一步还是奇数呢?现在target是14:
第一步:0 + 1 = 1
第二步:1 + 2 = 3
第三步:3 + 3 = 6
第四步:6 + 4 = 10
第五步:10 + 5 = 15
差值是1,往下走一步:
第六步:15 + 6 = 21
差值是7,再往下走一步:
第七步:21 + 7 = 28
差值是14,是偶数,那么target是14的就等于target是28的步数,即答案是7.也就是说,如果当前找到的刚好超过的target的数字num,步数是n,但是差值是奇数,而且下一个要加的数字是偶数,那么就还得再加一步,那么结果就是n+2。

所以,我们算出来,要走n步走到num,num大于等target,计算出差值diff = num - target

diff为偶数,直接返回n;
diff为奇数:
1. 下一步n + 1为奇数,那么返回n + 1
2. 下一步n + 1为偶数,返回n + 2

 

class Solution {
    public int reachNumber(int target) {
        target = Math.abs(target);
        int res = 0, sum = 0;
        while (sum < target) {
            ++res;
            sum += res;
        }
        int diff = sum - target;
        if (diff % 2 == 0) {
            return res;
        } else {
            if (res % 2 == 0) {
                return res + 1;
            } else {
                return res + 2;
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, I can help you with that. Here's an implementation of the Dice class: ```python import random class Dice: def __init__(self, num_sides): self.num_sides = num_sides def roll(self): return random.randint(1, self.num_sides) ``` This class has a constructor that takes in the number of sides of the dice and a roll method that returns a random number between 1 and the number of sides. To create a simple game using this class, we can do the following: ```python num_players = int(input("Enter the number of players: ")) num_sides = int(input("Enter the number of sides on the dice: ")) winning_score = int(input("Enter the winning score: ")) players = [] for i in range(num_players): players.append({'id': i+1, 'score': 0, 'rolls': 0, 'dice': Dice(num_sides)}) winner = None while not winner: for player in players: roll = player['dice'].roll() player['score'] += roll player['rolls'] += 1 print(f"Player {player['id']} rolled a {roll}. Current score: {player['score']}") if player['score'] >= winning_score: winner = player break print(f"\nPlayer {winner['id']} won with a score of {winner['score']} after {winner['rolls']} rolls.") ``` This code prompts the user for the number of players, the number of sides on the dice, and the winning score. It then creates a list of player dictionaries, each containing an ID, score, number of rolls, and a Dice object. The game loop iterates through each player, rolls their dice, updates their score and number of rolls, and checks if they have reached the winning score. If a player has reached the winning score, the game loop ends and the winner is announced.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值