Skip to content

Commit 821a026

Browse files
authored
Update sort-integers-by-the-power-value.py
1 parent 0721181 commit 821a026

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Python/sort-integers-by-the-power-value.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66

77
class Solution(object):
8-
lookup = {}
8+
dp = {}
99

1010
def getKth(self, lo, hi, k):
1111
"""
@@ -39,16 +39,19 @@ def partition_around_pivot(left, right, pivot_idx, nums, compare):
3939

4040
def power_value(x):
4141
y = x
42-
if x not in Solution.lookup:
42+
if x not in Solution.dp:
4343
result = 0
4444
while x > 1:
4545
result += 1
4646
if x%2:
4747
x = 3*x + 1
4848
else:
4949
x //= 2
50-
Solution.lookup[y] = result
51-
return Solution.lookup[y], y
50+
if x in Solution.dp:
51+
result += Solution.dp[x]
52+
break
53+
Solution.dp[y] = result
54+
return Solution.dp[y], y
5255

5356
arr = map(power_value, range(lo, hi+1))
5457
nth_element(arr, k-1)
@@ -58,7 +61,7 @@ def power_value(x):
5861
# Time: O(nlogn)
5962
# Space: O(n)
6063
class Solution2(object):
61-
lookup = {}
64+
dp = {}
6265

6366
def getKth(self, lo, hi, k):
6467
"""
@@ -69,15 +72,18 @@ def getKth(self, lo, hi, k):
6972
"""
7073
def power_value(x):
7174
y = x
72-
if x not in Solution2.lookup:
75+
if x not in Solution2.dp:
7376
result = 0
7477
while x > 1:
7578
result += 1
7679
if x%2:
7780
x = 3*x + 1
7881
else:
7982
x //= 2
80-
Solution2.lookup[y] = result
81-
return Solution2.lookup[y], y
83+
if x in Solution2.dp:
84+
result += Solution2.dp[x]
85+
break
86+
Solution2.dp[y] = result
87+
return Solution2.dp[y], y
8288

8389
return sorted(range(lo, hi+1), key=power_value)[k-1]

0 commit comments

Comments
 (0)