800. Similar RGB Color

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 > 0color[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.

思路:不如全部找到所有可能,然后求解所有的

class Solution:
    def similarRGB(self, color):
        """
        :type color: str
        :rtype: str
        """
        r,g,b = int(color[1:3],16), int(color[3:5],16), int(color[5:7],16)
        a = ['00','11','22','33','44','55','66','77','88','99','aa','bb','cc','dd','ee','ff']
        p = [(a[i],a[j],a[k]) for i in range(16) for j in range(16) for k in range(16)]
        res, min = '', 9999999
        for s in p:
            d = (int(s[0],16)-r)**2 + (int(s[1],16)-g)**2 + (int(s[2],16)-b)**2
            if min>d:
                min=d
                res=s
        return '#'+''.join(res)
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值