800. Similar RGB Color π
DifficultyEasy
Description
The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.
- For example,
"#15c"is shorthand for the color"#1155cc".
The similarity between the two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)2 - (CD - WX)2 - (EF - YZ)2.
Given a string color that follows the format "#ABCDEF", return a string represents the color that is most similar to the given color and has a shorthand (i.e., it can be represented as some "#XYZ").
Any answer which has the same highest similarity as the best answer will be accepted.
Example 1:
Input: color = "#09f166" Output: "#11ee66" Explanation: The similarity is -(0x09 - 0x11)2 -(0xf1 - 0xee)2 - (0x66 - 0x66)2 = -64 -9 -0 = -73. This is the highest among any shorthand color.
Example 2:
Input: color = "#4e3fe1" Output: "#5544dd"
Constraints:
color.length == 7color[0] == '#'color[i]is either digit or character in the range['a', 'f']fori > 0.
Solutions
Solution 1
Thinking
A shorthand color uses only channel values \(00,11,\ldots,ff\), i.e. multiples of \(17\). Similarity is the sum of squared channel differences, and the three channels do not interact, so enumerating all \(16^3\) shorthand colors is unnecessary.
Write a channel \(q\) as \(17y+z\). If the remainder \(z>8\), round up to the next multiple; otherwise keep the current one. Applying this independently to the three channels yields the closest shorthand color.
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |