Skip to content

Commit 60026dd

Browse files
committed
Time: 111 ms (100%), Space: 18.6 MB (100%) - LeetHub
1 parent f1e2ef1 commit 60026dd

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
from typing import List
4+
import bisect
5+
6+
7+
class Solution:
8+
def minOperations(self, nums: List[int]) -> List[int]:
9+
palindromeSet = set()
10+
11+
for length in range(1, 14):
12+
halfLen = (length + 1) // 2
13+
start = 1 << (halfLen - 1)
14+
end = 1 << halfLen
15+
for half in range(start, end):
16+
s = bin(half)[2:]
17+
if length % 2 == 0:
18+
pal = s + s[::-1]
19+
else:
20+
pal = s + s[-2::-1]
21+
val = int(pal, 2)
22+
if val <= 5000:
23+
palindromeSet.add(val)
24+
25+
palindromeSet = sorted(palindromeSet)
26+
27+
result = []
28+
for num in nums:
29+
pos = bisect.bisect_left(palindromeSet, num)
30+
31+
best = float('inf')
32+
33+
if pos < len(palindromeSet):
34+
best = min(best, abs(palindromeSet[pos] - num))
35+
if pos > 0:
36+
best = min(best, abs(palindromeSet[pos - 1] - num))
37+
38+
result.append(best)
39+
40+
return result
41+
42+
43+
nums = [1, 2, 4]
44+
print(Solution().minOperations(nums))
45+
nums = [6, 7, 12]
46+
print(Solution().minOperations(nums))

0 commit comments

Comments
 (0)