LeetCode 754. Reach a Number C++

1692 ワード

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].

  • Approach
    1.これは法則を探す問題で、最初は深く探したり広く探したりしようとしたが、数字がまだ2桁に達していないうちに、もう爆発してしまった.涙が出て、テーマの大意は明らかだ.0からtargetまで少なくとも何回、i回目にi歩を歩いた.2.私たちが0~7回出力したときにどこまで行けるか
    0
    -1 1
    -3 -1 1 3
    -6 -4 -2 0 0 2 4 6
    -10 -8 -6 -4 -4 -2 -2 0 0 2 2 4 4 6 8 10
    -15 -13 -11 -9 -9 -7 -7 -5 -5 -5 -3 -3 -3 -1 -1 -1 1 1 1 3 3 3 5 5 5 7 7 9 9 11 13 15
    -21 -19 -17 -15 -15 -13 -13 -11 -11 -11 -9 -9 -9 -9 -7 -7 -7 -7 -5 -5 -5 -5 -3 -3 -3 -3 -3 -1 -1 -1 -1 -1 1 1 1 1 1 3 3 3 3 3 5 5 5 5 7 7 7 7 9 9 9 9 11 11 11 13 13 15 15 17 19 21
    

    3.そこから2つの点がわかります.
  • の左右の両側はこの行の最小値と最大値
  • である.
  • 行のデジタルパリティ一致
  • 4.したがって、targetよりちょうど大きい値まで加算すればよいが、パリティが存在するため、行のパリティがtargetと一致するまで判断を続ける
    Code
    class Solution {
    public:
    	int reachNumber(int target) {
    		target = abs(target);
    		int step = 0, sum = 0;
    		while (sum < target || (sum - target) % 2 != 0) {
    			sum += ++step;
    		}
    		return step;
    	}
    };