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. 逆向破解之160个CrackMe —— 007

    CrackMe —— 007 160 CrackMe 是比较适合新手学习逆向破解的CrackMe的一个集合一共160个待逆向破解的程序 CrackMe:它们都是一些公开给别人尝试破解的小程序,制作 c ...

  2. HDU - 3535:AreYouBusy (分组背包)

    题意:给你n个工作集合,给你T的时间去做它们.给你m和s,说明这个工作集合有m件事可以做,它们是s类的工作集合(s=0,1,2,s=0说明这m件事中最少得做一件,s=1说明这m件事中最多只能做一件,s ...

  3. springboot项目报错Could not resolve placeholder 'datasource.type' in value "${datasource.type}"解决办法

    一,首先确认数据库的连接信息是否都正确,数据库能否正常连接(例如用客户端能连接上):二,确认配置文件中datasource.type配置是否正确,此处我们公司用的阿里的是com.alibaba.dru ...

  4. 怎样把txt文档转换成csv文件?

    其实csv就是逗号隔开的一行一行的数据, 如果每行数据中都是用逗号分隔的,直接把文件后缀txt改成csv就行了. 用python搞定: import numpy as np import pandas ...

  5. git工具免密拉取、推送

    很苦恼每次都要配置明文密码才能正常工作 其实也可以配置成非明文 打开控制面板 →用户账号 管理 Windows凭证 对应修改响应网址即可  

  6. (4)ardunio 矩阵求解官方库改造,添加逆的求解

    多此一举,原来官方库给了求逆的函数,在源码里 除此之外,还有转置矩阵,只不过样例没显示出来. //Matrix Inversion Routine // * This function inverts ...

  7. jsp大附件上传,支持断点续传

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...

  8. learning java 读写其他进程的数据

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public ...

  9. 关于java项目跑着跑着就挂掉的问题

    部署项目后,安装redis,从redis中获取数据,或一些数据库查询操作,服务器cpu和内存占用率突增.

  10. 75: libreoj #10028 双向宽搜

    $des$ 实现一个bfs $sol$ 写了一个双向bfs #include <bits/stdc++.h> using namespace std; #define Rep(i, a, ...