No.11 Container With Most Water 装最多的水
Question:
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 linei 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.
问题不是求梯形面积!而是求最多能装多少水,所以其实是求一个短板*距离的最大值。
思路:
肯定不能用暴力解法啦。所以选择贪心算法,或者就叫双指针法。
1. 距离越远面积越大,所以指针放在一头一尾
2. 面积受短边制约,所以移动短边所在的指针
3. 当指针相遇则停止,返回计算结果
代码:
public int maxArea(int[] height) {
int result = 0;
int i = 0;
int j= height.length - 1;
while(i<j){
int temp = getArea(height[i],height[j],j-i);
result=temp>result?temp:result;
if(height[i]>height[j]) j--;
else i++;
}
return result;
}
private int getArea(int frist,int second,int distance){
return distance*Math.min(frist,second);
}
No.12 Integer to Roman
1~3999 罗马数字。罗马数字规则看百度百科就行了,不过有剧透。
一共四位数,得出每一位的数字然后按照规则转写,最后连起来就可以了
public String intToRoman(int num) {
String result = "";
String[][] roman = {
{"","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"}};
result+=roman[3][num/1000];
result+=roman[2][num/100%10];
result+=roman[1][num/10%10];
result+=roman[0][num%10];
return result;
}