File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
December_LeetCode_Challenge Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ You are standing at position 0 on an infinite number line . There is a goal at position target .
2+
3+ On each move , you can either go left or right . During the n - th move (starting from 1 ),
4+ you take n steps .
5+
6+ Return the minimum number of steps required to reach the destination .
7+
8+ Example 1 :
9+ Input : target = 3
10+ Output : 2
11+ Explanation :
12+ On the first move we step from 0 to 1.
13+ On the second step we step from 1 to 3.
14+
15+ Example 2 :
16+ Input : target = 2
17+ Output : 3
18+ Explanation :
19+ On the first move we step from 0 to 1.
20+ On the second move we step from 1 to - 1.
21+ On the third move we step from - 1 to 2.
22+
23+ Note :
24+ target will be a non - zero integer in the range [- 10 ^ 9 , 10 ^ 9 ].
25+
26+
27+
28+ # O(target^1/2) Time and O(1) Space
29+ class Solution :
30+ def reachNumber (self , target : int ) - > int :
31+
32+ sum_val = 0
33+ steps = 0
34+
35+ target = abs (target )
36+
37+ while sum_val < target :
38+ sum_val += steps
39+ steps += 1
40+
41+
42+ while (sum_val - target ) % 2 == 1 :
43+ sum_val += steps
44+ steps += 1
45+
46+ return steps - 1
47+
48+
49+ class Solution (object ):
50+ def reachNumber (self , target ):
51+ target = abs (target )
52+ k = 0
53+ while target > 0 :
54+ k += 1
55+ target -= k
56+
57+ return k if target % 2 == 0 else k + 1 + k % 2
You can’t perform that action at this time.
0 commit comments