leetcode12&13

来源:互联网 发布:c语言的应用范围 编辑:程序博客网 时间:2024/05/22 15:47

1、Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字转数字
I 1
X 10
C 100
M 1000
V 5
L 50
D 500
任意两个罗马数字:
右边大于左边时,右边减左边;否则相加;上面带横线,就×1000。
运算顺序:从左往右

class Solution {public:    int romanToInt(string s) {        unordered_map<char,int> map;        map['I'] = 1;        map['X'] = 10;        map['C'] = 100;        map['M'] = 1000;        map['V'] = 5;        map['L'] = 50;        map['D'] = 500;        int result = map[s[0]];        for(int i = 0; i < s.size()-1; i++){            if(map[s[i]] < map[s[i+1]])                result += map[s[i+1]] - 2*map[s[i]];            else                result += map[s[i+1]];        }        return result;    }};

~~想到要存一对数据时可以考虑容器存pair,不过哈希表可以高效的访问关联数据key-value,能仅通过键名来快速的取回和赋值。且插入、删除、查找等,都是稳定的时间复杂度,即O(log n)。

2 Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

class Solution {public:    string intToRoman(int num) {        char* str[4][10] = {            {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, //0-9            {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, //10-90            {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, //100-900            {"", "M", "MM", "MMM"} //1000-3000        };        string val = ""; //取每一位然后字符相加        val += str[3][num / 1000 % 10];        val += str[2][num / 100  % 10];        val += str[1][num / 10   % 10];        val += str[0][num        % 10];        return val;    }};
0 0
原创粉丝点击