[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:
coloris a string of length7.coloris a valid RGB color: fori > 0,color[i]is a hexadecimal digit from0tof- 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 相似的红绿蓝颜色的更多相关文章
- [LeetCode] Similar RGB Color 相似的红绿蓝颜色
In the following, every capital letter represents some hexadecimal digit from 0 to f. The red-green- ...
- 【LeetCode】800. Similar RGB Color 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...
- FPGA驱动LCD显示红绿蓝彩条
实验目的:先简单熟悉LCD灯的驱动和时序图的代码实现.设计功能是让LCD显示红绿蓝三种颜色,即三个彩带.本次实验比较容易实现,主要是对LCD驱动时序图的理解和时序参数的配置. 实验条件:1.LCD原理 ...
- 阶段小项目1:循环间隔1秒lcd显示红绿蓝
#include<stdlib.h>#include<stdio.h>#include<string.h>#include<error.h>#inclu ...
- Hierarchical clustering:利用层次聚类算法来把100张图片自动分成红绿蓝三种色调—Jaosn niu
#!/usr/bin/python # coding:utf-8 from PIL import Image, ImageDraw from HierarchicalClustering import ...
- C#Color对象的使用介绍及颜色对照表
原文地址 http://blog.sina.com.cn/s/blog_3e1177090101bzs3.html 今天用到了特转载 NET框架中的颜色基于4种成份,透明度,红,绿和蓝.每一种成份都 ...
- RGB Color Codes Chart
RGB Color Codes Chart RGB颜色空间 RGB颜色空间或RGB颜色系统,从红色.绿色和蓝色的组合中构造所有颜色. 红色.绿色和蓝色各使用8位,它们的整数值从0到255.这使得256 ...
- 【AGC025B】RGB Color
[AGC025B]RGB Color 题面描述 Link to Atcoder Link to Luogu Takahashi has a tower which is divided into \( ...
- (转)如何根据RGB值来判断这是种什么颜色?
如何根据RGB值来判断这是种什么颜色? 下面介绍几种典型颜色的RGB值,格式为:颜色(R,G,B). 想象一下有红.绿.蓝三盏射灯打出三束光. 这三束光叠加在一起时产生白色,如果三盏灯的亮度都减半就产 ...
随机推荐
- Centos7-Gnome安装
查看grouplist yum grouplist 安装gnome yum groupinstall "GNOME Desktop" root用户权限下,设置centos系统默认的 ...
- ARTS-week7
Algorithm 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. Two Sum 编写一个 SQL 查询,满足条件:无论 ...
- robot framework 笔记(四),使用时遇到的问题
背景: 使用rf遇到的一些问题汇总 一:跑WEBUI的时候报错: [ WARN ] Keyword 'Capture Page Screenshot' could not be run on fail ...
- 如何有效使用Project(2)——进度计划的执行与监控
继上次的的<编制进度计划.保存基准>继续讲解如何对计划进行执行和监控. 计划执行即:反馈实际进度.反馈工作消耗(本文只考虑工时,不考虑成本).提出计划变更请求.如果你的企业实施了专门的PM ...
- 为什么管理人员都喜欢用Visio画图
一.形状数据一体化 这是管理者最喜欢的功能了,这也Visio的最核心的功能: 操作如下: 例如流程中的步骤.开始日期或结束日期.成本.设备部件等.数字.图标.颜色.标志和进度条等图形有助于快速方便地浏 ...
- idea常用设置汇总
https://www.cnblogs.com/wangmingshun/p/6427088.html
- [VSCode] Adding Custom Syntax Highlighting to a Theme in VSCode
VSCode Themes are a quick way to update the color scheme and syntax highlighting of your code, but y ...
- 实训作业5(lang、util)
实验内容和原理: 1.将布尔型.整型.长整型.双精度型作为参数,实例化相应的包装类对象,并输出对象的数值. package 包装; public class integer { public stat ...
- wget递归下载网站资源
wget -r -p -np -k http://archive.openwrt.org/barrier_breaker/14.07/ramips/mt7620a/packages/ 在下载https ...
- 限流神器之-Guava RateLimiter 实战
前段时间,项目中需要对某些访问量较高的路径进行访问并发数控制,以及有些功能,比如Excel导出下载功能,数据量很大的情况下,用户不断的点击下载按钮,重复请求数据库,导致线上数据库挂掉.于是在这样的情况 ...