1. Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
主要是按区间处理每一位digit1<=digit<=3
digit==4
digit==5
5<digit<=8
digit==9
string intToRoman(int num) {
char symbol[7] = {'I','V','X','L','C','D','M'};
string roman;
int scale = 1000;
for(int i=6;i>=0;i-=2){
int digit = num/scale;
if(digit!=0){
if(digit<=3){
roman.append(digit,symbol[i]);
}else if(digit == 4){
roman.append(1,symbol[i]);
roman.append(1,symbol[i+1]);
}else if(digit == 5){
roman.append(1,symbol[i+1]);
}else if(digit<=8){
roman.append(1,symbol[i+1]);
roman.append(digit-5,symbol[i]);
}else if(digit == 9){
roman.append(1,symbol[i]);
roman.append(1,symbol[i+2]);
}
}
num = num%scale;
scale /=10;
}
return roman;
}
2.Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:从左往右扫描,如果当前值比前一个大,则将当前值与前一值得差加入结果
否则,直接将当前值加入结果中
inline int c2n(char c){//inline function
switch(c){
case'I':return 1;
case'V':return 5;
case'X':return 10;
case'L':return 50;
case'C':return 100;
case'D':return 500;
case'M':return 1000;
default:return 0;
}
}
int romanToInt(string s) {
int result=0;
for(int i=0;i<s.size();i++){
if(i>0 && c2n(s[i])>c2n(s[i-1])){
result += (c2n(s[i])-2*c2n(s[i-1]));
}else{
result+=c2n(s[i]);
}
}
return result;
}
2. Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Analysis:
Scan the rating array from left to right and then from right to left. In every scan just consider the rising order(left->right: r[i]>r[i-1] or right->left: r[i]>r[i+1]), assign +1 candies to the rising position.
The final candy array is the maximum (max(right[i],left[i])) in each position.
The total candies is the sum of the final candy array.
时间复杂度是O(n).
int candy(vector<int> &ratings) {
int result =0;
vector<int> lc(ratings.size(),1);
vector<int> rc(ratings.size(),1);
for(int i=1;i<ratings.size();i++){
if(ratings[i]>ratings[i-1])
lc[i] = lc[i-1]+1;
}
for(int i=ratings.size()-2;i>=0;i--){
if(ratings[i]>ratings[i+1])
rc[i] = rc[i+1]+1;
}
for(int i=0;i<ratings.size();i++){
result+=max(lc[i],rc[i]);
}
return result;
}