[
string
math
]
Leetcode 0800 Similar RGB Color
Problem statement
https://leetcode.com/problems/similar-rgb-color/
Solution
For each channel (R, G, B)
: we need to find closest color: we will use closest(s)
function for this. We need to find the closest between given color s
and colors 00, 11, 22, ... , ff
: which are represented as 0, 17, 34, ... 17 * 15
in decimal base. When we found closest, we transform it back, using hex
function. Finally, we go through 3
parts and create number.
Complexity
Time complexity is O(16 * 3)
, because for each of 3
blocks we check 16
different options.
Code
class Solution(object):
def similarRGB(self, color):
def closest(s):
t = min(range(16), key = lambda x: abs(17*x - int(s, 16)))
return hex(t)[2:]*2
return "#" + "".join(closest(color[2*i+1:2*i+3]) for i in range(3))
Remark
Actually, we can check not 16
options, but only two, but here it is not worth it, complexity is already very small.