LeetCode No.11 ~No.12

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;
    }

     

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值