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;
}
};

  

 

All LeetCode Questions List 题目汇总

[LeetCode] 800. Similar RGB Color 相似的红绿蓝颜色的更多相关文章

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

    In the following, every capital letter represents some hexadecimal digit from 0 to f. The red-green- ...

  2. 【LeetCode】800. Similar RGB Color 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...

  3. FPGA驱动LCD显示红绿蓝彩条

    实验目的:先简单熟悉LCD灯的驱动和时序图的代码实现.设计功能是让LCD显示红绿蓝三种颜色,即三个彩带.本次实验比较容易实现,主要是对LCD驱动时序图的理解和时序参数的配置. 实验条件:1.LCD原理 ...

  4. 阶段小项目1:循环间隔1秒lcd显示红绿蓝

    #include<stdlib.h>#include<stdio.h>#include<string.h>#include<error.h>#inclu ...

  5. Hierarchical clustering:利用层次聚类算法来把100张图片自动分成红绿蓝三种色调—Jaosn niu

    #!/usr/bin/python # coding:utf-8 from PIL import Image, ImageDraw from HierarchicalClustering import ...

  6. C#Color对象的使用介绍及颜色对照表

    原文地址  http://blog.sina.com.cn/s/blog_3e1177090101bzs3.html 今天用到了特转载 NET框架中的颜色基于4种成份,透明度,红,绿和蓝.每一种成份都 ...

  7. RGB Color Codes Chart

    RGB Color Codes Chart RGB颜色空间 RGB颜色空间或RGB颜色系统,从红色.绿色和蓝色的组合中构造所有颜色. 红色.绿色和蓝色各使用8位,它们的整数值从0到255.这使得256 ...

  8. 【AGC025B】RGB Color

    [AGC025B]RGB Color 题面描述 Link to Atcoder Link to Luogu Takahashi has a tower which is divided into \( ...

  9. (转)如何根据RGB值来判断这是种什么颜色?

    如何根据RGB值来判断这是种什么颜色? 下面介绍几种典型颜色的RGB值,格式为:颜色(R,G,B). 想象一下有红.绿.蓝三盏射灯打出三束光. 这三束光叠加在一起时产生白色,如果三盏灯的亮度都减半就产 ...

随机推荐

  1. CentOS6.5配置

    关闭防火墙 查看防火墙状态 /etc/init.d/iptables status 停止 /etc/init.d/iptables stop 开机不启动 chkconfig iptables off ...

  2. idea去除mybatis的xml那个恶心的绿色背景

    https://my.oschina.net/qiudaozhang/blog/2877536

  3. Flume架构以及应用介绍(转)

    在具体介绍本文内容之前,先给大家看一下Hadoop业务的整体开发流程: 从Hadoop的业务开发流程图中可以看出,在大数据的业务处理过程中,对于数据的采集是十分重要的一步,也是不可避免的一步,从而引出 ...

  4. StringTokenizer字符串分解器

    示例: StringTokenizer st = new StringTokenizer(key, ",", false); while (st.hasMoreTokens()) ...

  5. 更新GitHub上自己 Fork 的代码与原作者的项目进度一致

    在GitHub上我们会去fork别人的一个项目,这就在自己的Github上生成了一个与原作者项目互不影响的副本,自己可以将自己Github上的这个项目再clone到本地进行修改,修改后再push,只有 ...

  6. [51Nod 1222] - 最小公倍数计数 (..怎么说 枚举题?)

    题面 求∑k=ab∑i=1k∑j=1i[lcm(i,j)==k]\large\sum_{k=a}^b\sum_{i=1}^k\sum_{j=1}^i[lcm(i,j)==k]k=a∑b​i=1∑k​j ...

  7. 微信H5中禁止分享好友及分享到朋友圈的方法

    我们可以直接把以下代码加入到页面中,即可限制住各类分享. <script> function onBridgeReady() { WeixinJSBridge.call('hideOpti ...

  8. 小程序支付及H5支付前端代码小结

    小程序支付和H5支付前端都不需要引入其他的js , 只需要后台将相关的参数 ( timeStamp: '', nonceStr: '', package: '', signType: 'MD5', p ...

  9. 使用readthedocs 发布 sphinx doc文档

    readthedocs 是由社区驱动的开源sphinx doc 托管服务,我们可以用来方便的构建以及发布文档 这是一个简单的demo 项目,使用了用的比较多的sphinx_rtd_theme 主题,主 ...

  10. (浙江金华)Day 1 组合数计数

    目录 Day 1 组合计数 1.组合数 (1).C(n,m) 读作n选m,二项式系数 : (2).n个东西里选m个的方案数 不关心选的顺序: (3).二项式系数--->多项式系数: 2.组合数计 ...