[LeetCode] 800. Similar RGB Color 相似的红绿蓝颜色

Posted 轻风舞动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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.

大写字母组成的16进制字符串表示RGB颜色,可以简写为‘#XYZ‘形式的,两个颜色的相似度由给的公式计算得出。给一个颜色,求和它最相似的颜色,返回的是7个字符表示的颜色。

解法1:暴力brute force.

解法2:

解法3: 将字符串分为3个部分,对每个部分找个最相近的 ‘XX’ 格式的值即可。对于每一个 ‘XY’ 值,最近的一定在 ‘XX’, ‘(X-1)(X-1)’, ‘(X+1)(X+1)’ 之中,所以计算出这三个值取最近的即可。

Java:  暴力

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)
     

Python: 暴力

class Solution(object):
    def similarRGB(self, color):
        """
        :type color: str
        :rtype: str
        """
        ir, ig, ib = (int(color[x: x+2], 16)
                      for x in (1, 3, 5))
        ans = ()
        delta = 0x7FFFFFFF
        for r in range(16):
            for g in range(16):
                for b in range(16):
                    ndelta = sum((ic - c * 17) ** 2
                                 for ic, c in zip((ir, ig, ib), (r, g, b)))
                    if ndelta < delta:
                        delta = ndelta
                        ans = r, g, b
        return ‘#‘ + ‘‘.join(hex(c)[2] * 2 for c in ans) 

Python: 解法2 Time:  O(1), Space: O(1)

class Solution(object):
    def similarRGB(self, color):
        """
        :type color: str
        :rtype: str
        """
        def rounding(color):
            q, r = divmod(int(color, 16), 17)
            if r > 8: q += 1
            return ‘{:02x}‘.format(17*q)

        return ‘#‘ +                 rounding(color[1:3]) +                 rounding(color[3:5]) +                 rounding(color[5:7])  

Python:  解法3

def similarRGB(self, color):
    ret = ‘#‘
    for i in range(1, 6, 2):
        c1, c2 = [int(_) if ‘0‘<=_<=‘9‘ else 10+ord(_)-ord(‘a‘) for _ in color[i:i+2]]
        c = c1+sorted(enumerate([abs((c1*16+c2)-(x*16+x)) for x in [c1-1, c1, c1+1]]), key=lambda _:_[1])[0][0]-1
        ret += str(c)*2 if c<=9 else chr(c-10+ord(‘a‘))*2
    return ret  

C++: 暴力,T: O(3 * 16)  S: O(1)

class Solution {
public:
  string similarRGB(string color) {
    const string hex{"0123456789abcdef"};
    vector<int> rgb(3, 0);
    for (int i = 0; i < 3; ++i)
      rgb[i] = hex.find(color[2 * i + 1]) * 16 + hex.find(color[2 * i + 2]);
    
    string ans(7, ‘#‘);    
    for (int i = 0; i < 3; ++i) {
      int best = INT_MAX;
      for (int j = 0; j < 16; ++j) {
        int diff = abs(j * 16 + j - rgb[i]);
        if (diff >= best) continue;
        best = diff;
        ans[2 * i + 1] = ans[2 * i + 2] = hex[j];
      }
    }
    return ans;
  }
};

C++:

class Solution {
public:
    string similarRGB(string color) {
        return "#" + helper(color.substr(1, 2)) + helper(color.substr(3, 2)) + helper(color.substr(5, 2));
    }
    string helper(string str) {
        string dict = "0123456789abcdef";
        int num = stoi(str, nullptr, 16);
        int idx = num / 17 + (num % 17 > 8 ? 1 : 0);
        return string(2, dict[idx]);
    }
};

C++:

class Solution {
public:
    string similarRGB(string color) {
        for (int i = 1; i < color.size(); i += 2) {
            int num = stoi(color.substr(i, 2), nullptr, 16);
            int idx = num / 17 + (num % 17 > 8 ? 1 : 0);
            color[i] = color[i + 1] = (idx > 9) ? (idx - 10 + ‘a‘) : (idx + ‘0‘);
        }
        return color;
    }
};

  

 

以上是关于[LeetCode] 800. Similar RGB Color 相似的红绿蓝颜色的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] Leaf-Similar Trees

[LeetCode] 872. Leaf-Similar Trees

Leetcode_easy872. Leaf-Similar Trees

Leetcode 872. Leaf-Similar Trees

[LeetCode] Leaf-Similar Trees 叶结点相似的树

[LeetCode] Similar RGB Color 相似的红绿蓝颜色