题目:
思路:
1.用双指针分别从头跟末尾开始执行
2.如果左边的高度小于右边时向右进一,右边小于左边向左进一,同时算出体积,使用max函数比较大小,循环完后出差最大体积
class Solution {
public int maxArea(int[] height) {
int left=0;
int right=height.length-1;
int res=0;
while(left<right){
int area=Math.min(height[left],height[right])*(right-left);
res=Math.max(res,area);
if(height[left]<height[right]){
left++;
}else{
right--;
}
}
return res;
}
}
题目:
思路:.
1.可以使用贪心算法,先定义13个罗马数字代表的数值数字
2.从高位到低位一次循环,选最大的值
3.拼接罗马数字
class Solution {
public String intToRoman(int num) {
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] strings = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder builder = new StringBuilder();
for (int i=0; i<values.length; i++) {
while (num >= values[i]) {
num -= values[i];
builder.append(strings[i]);
}
}
return builder.toString();
}
}