Container With Most Water
问题描述
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 and n is at least 2.
分析
可以使用分治法等求解,将问题的解看为三种情况:区间最左边,区间最右边,区间中间,递归的计算每个区间的解,然后整合起来。笔者这里求解的方法是利用贪心算法的思路,从两边开始向中间遍历,依次寻找height最高的两个求他们结果,然后与前一结果比较。
解答
class Solution {
public:
int maxArea(vector<int>& height) {
int result = 0;
for (int i = 0, j = height.size() - 1; i < j; )
{
int area = 0;
if (height[i] > height[j])
{
area =(j - i) * height[j];
j--;
while (height[j] < height[j + 1])
j--;
}
else
{
area =(j - i) * height[i];
i++;
while (height[i] < height[i - 1])
i++;
}
if (area > result)
result = area;
}
return result;
}
};
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) {
const int radix[] = {1000, 900, 500, 400, 100, 90,50, 40, 10, 9, 5, 4, 1};
const string symbol[] = {"M", "CM", "D", "CD", "C", "XC","L", "XL", "X", "IX", "V", "IV", "I"};
string result = "";
for (int i = 0; num > 0; i++)
{
int count = num / radix[i];
num %= radix[i];
for ( ; count > 0; count--)
result += symbol[i];
}
return result;
}
};