12 - 26 - 27 - 80.
12. 整数转罗马数字
- 动态规划,减去上一个最大的特殊数字之后,加上已经得到的剩余数的表达式(慢且占空间大)
// 19.47
// 20.02
// 动规
class Solution {
public:
string intToRoman(int num) {
map<int, string> m = {{1,"I"},{4,"IV"},{5,"V"},{9,"IX"},{10,"X"},{40,"XL"},{50,"L"},{90,"XC"},{100,"C"},{400,"CD"},{500,"D"},{900,"CM"},{1000,"M"}};
vector<string> dp(num+1);
for(auto it = m.begin(); it != m.end() && it->first <= num; it++) {
if(it->first == num) return it->second;
dp[it->first] = it->second;
}
int last = 1;
for(int i = 2; i <= num; i++) {
if(dp[i] != "") {
last = i;
} else {
dp[i] = dp[last] + dp[i-last];
}
}
return dp.back();
}
};
- 贪心,逐个逐个减去比他大的特殊数字的表达式
class Solution {
public:
string intToRoman(int num) {
map<int, string, greater<int>> m =
{{1,"I"},{4,"IV"},{5,"V"},{9,"IX"},{10,"X"},{40,"XL"},{50,"L"},{90,"XC"},{100,"C"},{400,"CD"},{500,"D"},{900,"CM"},{1000,"M"}};
string ans;
for(auto it = m.begin(); it != m.end() && num != 0; it++) {
while(it->first <= num) {
ans += it->second;
num -= it->first;
}
}
return ans;
}
};
- 硬编码 - 把对应的每个数字的表达式写出来即可
(不过这是种取巧的方法,一旦数字较大就不可用)
/*
作者:int-myheart
链接:https://leetcode-cn.com/problems/integer-to-roman/solution/zhi-jie-an-zhao-mei-yi-wei-010de-qing-kuang-cun-ji/
来源:力扣(LeetCode)
*/
class Solution {
public:
string intToRoman(int num)
{
char* c[4][10] = {
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"}
};
string roman;
roman.append(c[3][num / 1000]);
roman.append(c[2][num / 100 % 10]);
roman.append(c[1][num / 10 % 10]);
roman.append(c[0][num % 10]);
return roman;
}
};
27. 移除元素
// 21.00
// 21.19
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if(nums.empty()) return 0;
int index = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != val) {
nums[index++] = nums[i];
}
}
return index;
}
};
26. 删除排序数组中的重复项
同上
// 21.27
// 21.30
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty()) return 0;
int i = 1;
for(int k = 1; k < nums.size(); k++) {
if(nums[k] != nums[k-1]) {
nums[i++] = nums[k];
}
}
return i;
}
};
80. 删除排序数组中的重复项 II
几乎同上
// 21.33
// 21.43
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty()) return 0;
int cnt, i;
cnt = i = 1;
for(int k = 1; k < nums.size(); k++) {
if(nums[k] == nums[k-1]) {
if(cnt < 2) {
cnt++;
nums[i++] = nums[k];
}
} else {
cnt = 1;
nums[i++] = nums[k];
}
}
return i;
}
};