forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stepping-numbers.py
55 lines (48 loc) · 1.51 KB
/
stepping-numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Time: O(logk + r), r is the size of result
# Space: O(k), k is the size of stepping numbers in [0, high]
import bisect
MAX_HIGH = int(2e9)
result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in xrange(1, MAX_HIGH):
if result[-1] >= MAX_HIGH:
break
d1 = result[i]%10 - 1
if d1 >= 0:
result.append(result[i]*10 + d1)
d2 = result[i]%10 + 1
if d2 <= 9:
result.append(result[i]*10 + d2)
result.append(float("inf"))
class Solution(object):
def countSteppingNumbers(self, low, high):
"""
:type low: int
:type high: int
:rtype: List[int]
"""
lit = bisect.bisect_left(result, low);
rit = bisect.bisect_right(result, high);
return result[lit:rit]
# Time: O(k + r), r is the size of result
# Space: O(k), k is the size of stepping numbers in [0, high]
class Solution2(object):
def countSteppingNumbers(self, low, high):
"""
:type low: int
:type high: int
:rtype: List[int]
"""
result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in xrange(1, high):
if result[-1] >= high:
break
d1 = result[i]%10 - 1
if d1 >= 0:
result.append(result[i]*10 + d1)
d2 = result[i]%10 + 1
if d2 <= 9:
result.append(result[i]*10 + d2)
result.append(float("inf"))
lit = bisect.bisect_left(result, low);
rit = bisect.bisect_right(result, high);
return result[lit:rit]