1. 题目
RGB 颜色用十六进制来表示的话,每个大写字母都代表了某个从 0 到 f 的 16 进制数。
RGB 颜色 “#AABBCC” 可以简写成 “#ABC” 。例如,"#15c" 其实是 “#1155cc” 的简写。
现在,假如我们分别定义两个颜色 "#ABCDEF"
和 "#UVWXYZ"
,则他们的相似度可以通过这个表达式 -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2
来计算。
那么给定颜色 “#ABCDEF”,请你返回一个与 #ABCDEF 最相似的 7 个字符代表的颜色,并且它是可以被简写形式表达的。(比如,可以表示成类似 “#XYZ” 的形式)
示例 1:
输入:color = "#09f166"
输出:"#11ee66"
解释:
因为相似度计算得出 -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73
这已经是所有可以简写的颜色中最相似的了
注意:
color 是一个长度为 7 的字符串
color 是一个有效的 RGB 颜色:对于仍和 i > 0,color[i] 都是一个在 0 到 f 范围的 16 进制数
假如答案具有相同的(最大)相似度的话,都是可以被接受的
所有输入、输出都必须使用小写字母,并且输出为 7 个字符
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/similar-rgb-color
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
2.1 暴力枚举
class Solution {
public:
string similarRGB(string color) {
string s1 = color.substr(1,2);
string s2 = color.substr(3,2);
string s3 = color.substr(5,2);
int a = stoi(s1,0,16);//转成10进制
int b = stoi(s2,0,16);
int c = stoi(s3,0,16);
vector<string> num = {"00","11","22","33","44","55","66","77","88",
"99","aa","bb","cc","dd","ee","ff"};
int i, j, k, x, y, z, maxsimilarity = INT_MIN, sim;
string ans;
for(i = 0; i < 16; ++i)
for(j = 0; j < 16; ++j)
for(k = 0; k < 16; ++k)
{
x = stoi(num[i],0,16);//转成10进制
y = stoi(num[j],0,16);
z = stoi(num[k],0,16);
sim = -(a-x)*(a-x)-(b-y)*(b-y)-(c-z)*(c-z);
if(sim > maxsimilarity)
{
maxsimilarity = sim;
ans = "#"+num[i]+num[j]+num[k];
}
}
return ans;
}
};
136 ms 6.3 MB
2.2 独立枚举
- 每两位是独立的,分别找出最相近的,拼接在一起
class Solution {
public:
string similarRGB(string color) {
string s1 = color.substr(1,2);
string s2 = color.substr(3,2);
string s3 = color.substr(5,2);
int a = stoi(s1,0,16);//转成10进制
int b = stoi(s2,0,16);
int c = stoi(s3,0,16);
vector<string> num = {"00","11","22","33","44","55","66","77","88",
"99","aa","bb","cc","dd","ee","ff"};
int maxsimilarity1 = INT_MIN, maxsimilarity2 = INT_MIN,
maxsimilarity3 = INT_MIN, sim1, sim2, sim3;
string ans1, ans2, ans3;
for(int i = 0, n; i < 16; ++i)
{
n = stoi(num[i],0,16);//转成10进制
sim1 = -(a-n)*(a-n);
sim2 = -(b-n)*(b-n);
sim3 = -(c-n)*(c-n);
if(sim1 > maxsimilarity1)
{
maxsimilarity1 = sim1;
ans1 = num[i];
}
if(sim2 > maxsimilarity2)
{
maxsimilarity2 = sim2;
ans2 = num[i];
}
if(sim3 > maxsimilarity3)
{
maxsimilarity3 = sim3;
ans3 = num[i];
}
}
return '#'+ans1+ans2+ans3;
}
};
0 ms 6.3 MB
长按或扫码关注我的公众号,一起加油、一起学习进步!