day1
按照 Leetcode社区 大佬提供的方法,开始我的Leetcode之旅,旨在在实践中增强自己解决实际问题的能力。
13.Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: “III”
Output: 3
Example 2:
Input: “IV”
Output: 4
Example 3:
Input: “IX”
Output: 9
Example 4:
Input: “LVIII”
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: “MCMXCIV”
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
分析
输入字符串可以看做是一个字符数组,首先建立一个罗马字符与数值对应的map,然后从左到右依次遍历各个字符,遍历中有以下要点:
1.如果当前被扫描字符数值小于或等于前一个字符数值,则为加法复合,sum += m[s[i]],此项从0开始判断使为了使索引统一,需要加入一个i == 0的或条件(或者在for循环前对sum进行赋值,少迭代一次);
2.如果当前被扫描字符大于前一个字符数值,则为减法复合,
sum += m[s[i+1]] - 2 * m[s[i]]。
最后输出sum前别忘了数值范围判断。
代码
java
class Solution {
public int romanToInt(String s) {
int sum = 0;
unordered_map<char,int> m = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
for(int i = 0; i < s.size(); i ++){
if(i == 0 || s[m[i]] <= s[m[i-1]]){
sum += m[s[i]];
}
if(s[m[i]] > s[m[i-1]]){
sum += m[s[i]] - 2 * m[s[i-1]];
}
}
if(sum < 1 || sum >3999){
return 0;
}
return sum;
}
}
C++
#include<iostream>
#include<string>
#include<map>
using namespace std;
class Solution {
public:
int romanToInt(string s) {
map<char, int> maps = { {'I',1}, {'V',5}, {'X', 10},{ 'L',50},{'C',100},{'D',500},{'M',1000} };
int sum = maps[s[0]];
for (int i = 1; i < s.size(); i++) {
if (maps[s[i]] > maps[s[i - 1]]) {
sum += maps[s[i]] - 2 * maps[s[i - 1]];
}
else {
sum += maps[s[i]];
}
}
if (sum < 1 || sum>3999) {
return 0;
}
return sum;
}
};
int main() {
Solution s;
string str;
while (cin >> str) {
int result = s.romanToInt(str);
cout << result << endl;
}
}
时间、空间复杂度分析
时间复杂度 | 空间复杂度 |
---|---|
O(n) | O(1) |
n表示数据规模,若数据规模增大,for循环的运行时间也会等比例增加,所以时间复杂度为O(n);
形参为数组,只需要为它分配一个存储由实参传送来的一个地址指针的空间,而函数体类的局部变量需要的存储空间也为常数级,所以整体来讲空间复杂度为O(1)。
心得
算法的空间复杂度总体来讲包括三方面:
1.存储算法程序代码占用的空间;
2.输入数据所占用的空间;
3.辅助变量所占用的空间。
其中1与算法的书写长度有关,2与解决的问题有关,所以我们评判算法的主要方法还是要关注第3点,3又包括两部分:
3.1 为算法参数表中形参变量分配的存储空间
3.2 为算法内局部变量分配的存储空间
在比较时要注意:这里的数据规模n不是指多加一份数据规模为n的数据使整体数据增多,而是将n变大,即该份数据增大的情况下分析算法时间与空间复杂度。