题目描述:
街上有 n 栋房子整齐地排成一列,每栋房子都粉刷上了漂亮的颜色。给你一个下标从 0 开始且长度为 n 的整数数组 colors ,其中 colors[i] 表示第 i 栋房子的颜色。
返回 两栋 颜色 不同 房子之间的 最大 距离。
第 i 栋房子和第 j 栋房子之间的距离是 abs(i - j) ,其中 abs(x) 是 x 的绝对值
思路:
一个是暴力解决,看注释了的那一部分;
另一个是贪心,先找到 找与最左边房子不同颜色的第一个房子,再找到 找与最右边颜色不同的第一个房子,比较这两个的大小,就为最终的答案了
class Solution {
public:
int maxDistance(vector<int>& colors) {
int i = 0, j = colors.size()-1;
//找与最右边颜色不同的第一个房子
int ans = 0, ans1 = 0;
while (colors[i] == colors[colors.size()-1]) {
i++;
}
ans = j-i;
//找与最左边房子不同颜色的第一个房子
while (colors[0] == colors[j]) {
j--;
}
ans = max(ans, j);
return ans;
// int ans = 0;
// for (int i = 0; i < colors.size(); ++i) {
// for (int j = i + 1; j < colors.size(); ++ j) {
// if (colors[i] != colors[j]) {
// ans = max(ans, abs(i-j));
// }
// }
// }
// return ans;
}
};
之前c语言版本做过了,现在做c++版本的
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int ans = 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i+=2) {
ans += nums[i];
}
return ans;
}
};
题目描述:
给你一个仅由数字 6 和 9 组成的正整数 num
。
你最多只能翻转一位数字,将 6 变成 9,或者把 9 变成 6 。
请返回你可以得到的最大数字。
思路:
先拆分数字(可以用栈,先进后出,正好符合高位在前的特点),
找到第一个不为9的数字改成9(在栈pop的过程中,找第一个不为9的数字,用一个flag打标记即可),
然后重组这个数字;
class Solution {
public:
int maximum69Number (int num) {
stack<int> stk;
int ret = 0;
while(num%10) {
stk.push(num%10);
num /= 10;
}
int flag = 1;
while(!stk.empty()) {
int tmp = stk.top();
stk.pop();
if(tmp != 9 && flag) {
tmp = 9;
flag = 0;
}
ret = ret*10 + tmp;
}
return ret;
}
};
题目描述:
由范围 [0,n] 内所有整数组成的 n + 1 个整数的排列序列可以表示为长度为 n 的字符串 s ,其中:
如果 perm[i] < perm[i + 1] ,那么 s[i] == 'I'
如果 perm[i] > perm[i + 1] ,那么 s[i] == 'D'
给定一个字符串 s ,重构排列 perm 并返回它。如果有多个有效排列perm,则返回其中 任何一个 。
思路:
碰到 I 就放小数字,更新小数字,碰到D就放大数字,更新大数字,最后别忘了把最后一个数字添加上。
class Solution {
public:
vector<int> diStringMatch(string s) {
int l = 0, r = s.size();
vector<int> ans;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'I') {
ans.push_back(l++);
} else {
ans.push_back(r--);
}
}
ans.push_back(l);
return ans;
}
};