011 Container With Most Water
1. 原题
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
2. 释题
该题比较简单,在数组头尾做两个标记,高度小的那个标记往中间缩,企图找到更大的面积。
3. 答案
class Solution {
public:
int maxArea(vector<int>& height)
{
if(height.size() < 2)
return 0;
int start = 0;
int end = height.size() - 1;
int maxAre = 0;
int area = 0;
int length = 0;
while(start < end)
{
length = end - start;
area = length * (height[start] < height[end] ? height[start] : height[end]);
if(area > maxAre)
{
maxAre = area;
}
if(height[start] < height[end])
{
start ++;
}
else
{
end --;
}
}
return maxAre;
}
};
012 Integer to Roman
1. 原题
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
2. 释题
该题比较简单,最好的方法简单粗暴,直接查表,该查表时就查表,不要吝啬一点点空间,1-3999的罗马数字就那么多,具体看代码。
3. 答案
class Solution {
public:
string intToRoman(int num)
{
string roman[][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 ret = "";
for(int i = 0; i < 4; i ++)
{
if(num == 0)
break;
ret = roman[i][num % 10] + ret;
num /= 10;
}
return ret;
}
};
013 Roman to Integer
1. 原题
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
2. 释题
该题是上一题的兄弟,做法依然是查表,不过这个表初始化的时候要动点脑筋,具体看代码。
3. 答案
class Solution {
public:
int romanToInt(string s) {
int table[26];
memset(table, 0, 26 * sizeof(int));
table['I' -65] = 1;
table['V' -65] = 5;
table['X' -65] = 10;
table['L' -65] = 50;
table['C' -65] = 100;
table['D' -65] = 500;
table['M' -65] = 1000;
int res = 0;
for(int i = 0; i < s.size(); i ++)
{
if(s[i] == 'I')
{
if(i < s.size() - 1 && (s[i + 1] == 'V' || s[i + 1] == 'X'))
res -= 1;
else
res += 1;
continue;
}
if(s[i] == 'X')
{
if(i < s.size() - 1 && (s[i + 1] == 'L' || s[i + 1] == 'C'))
res -= 10;
else
res += 10;
continue;
}
if(s[i] == 'C')
{
if(i < s.size() - 1 && (s[i + 1] == 'D' || s[i + 1] == 'M'))
res -= 100;
else
res += 100;
continue;
}
res += table[s[i] - 65];
}
return res;
}
};