Closest RGB Color
viaLeetCode
Problem A pixel colour is a 24-bit integer: three 8-bit channels (red, green, blue). Given a target colour and a list of available colours, return the colour from the list closest to the target.
Input / Output
- Input: int target, int[] palette (each a 24-bit RGB value).
- Output: the palette colour minimizing the distance to the target.
Constraints
- Palette up to 10^5; clarify tie-breaking (e.g. first/lowest value wins).
Example
- target = 0xFF0000 (pure red), palette = [0xEE0000, 0x00FF00] → 0xEE0000.
Expected approach
- Extract channels with shifts/masks: r = (c >> 16) & 0xFF, g = (c >> 8) & 0xFF, b = c & 0xFF. Use squared Euclidean distance (dr² + dg² + db²) — no sqrt needed for comparison — and a linear scan: O(n) time, O(1) space. Discussion: why treating the colour as one integer and comparing |a−b| is wrong (channel boundaries), and options for many queries (k-d tree over 3D channel space).
asked …