Leetcode第十二题——罗马数字转换
思路:贪心算法:及考虑当前步骤最大利益。
解法:
int[] values={1000,900,500,400,100,90,50,40,10,9,5,4,1}; String[] symbols={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; char[] chars=new char[17]; int idx=0; for (int i = 0; i < values.length; i++) { while(values[i]<=num&&num>0){ num-=values[i]; String s = symbols[i]; for(int schar=0;schar<s.length();schar++){ chars[idx++]=s.charAt(schar); } } } return new String(chars,0,idx); /* 时间复杂度:O(1),不随数字变化而变化 空间复杂度:O(1),字符数组总数是趋向于不变的,大体小于value数组长度 */