Press "Enter" to skip to content

Posts tagged as “rgb”

花花酱 LeetCode 800. Simple RGB Color

Problem

In the following, every capital letter represents some hexadecimal digit fromĀ 0Ā toĀ f.

The red-green-blue colorĀ "#AABBCC"Ā can be writtenĀ asĀ "#ABC"Ā inĀ shorthand.Ā  For example,Ā "#15c"Ā is shorthand for the colorĀ "#1155cc".

Now, say the similarity between two colorsĀ "#ABCDEF"Ā andĀ "#UVWXYZ"Ā isĀ -(AB - UV)^2 -Ā (CD - WX)^2 -Ā (EF - YZ)^2.

Given the colorĀ "#ABCDEF", return a 7 character colorĀ that is most similar toĀ #ABCDEF, and has a shorthand (that is, it can be represented as someĀ "#XYZ"

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.

Note:

  • colorĀ is a string of lengthĀ 7.
  • colorĀ is a valid RGB color: forĀ i > 0,Ā color[i]Ā is a hexadecimal digit fromĀ 0Ā toĀ f
  • Any answer which has the same (highest)Ā similarity as the best answer will be accepted.
  • All inputs and outputs should use lowercase letters, and the output is 7 characters.

Solution: Brute Force

R, G, B are independent, find the closest color for each channel separately.

Time complexity: O(3 * 16)

Space complexity: O(1)