自己刷leetcode的第二天1

来源:互联网 发布:八爪网络科技 知乎 编辑:程序博客网 时间:2024/04/27 20:34

1.reverse integer的问题

今天用了一个十分简单的题目入手作为开胃菜。不想依然犯了很严重的错误,真真是不应该啊

很简单的一个问题,由于自己的粗心,没有考虑周全。

关于溢出的问题,对数字的操作需要特别考虑这个问题,加减乘除以后都可能产生溢出,对于溢出,我们要用try和catch来解决

其次,对于翻转一个integer like 100 反转后的结果应该是1而不是001。


2.container with most water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

解释:

因为一个container能装的水的多少实际上是取决于短板

要使一个container装的水变多,那么肯定需要在短板上进行处理,此题当中,当然就是要移动短板

如果短板移动过后,能装的水变多了,那么更新容量,如果没有变多活着变少了,那么便不移动短板,就是这么简单

只要两个短板不相遇或者不交叉,那么就可以移动

public int maxArea(int[] height) {int left=0;int right=height.length-1;int maxVolumn=min(height[left],height[right])*(right-left);while(left<right){if(height[left]<height[right]){left++;int m=height[left]>height[right]?height[right]*(right-left):height[left]*(right-left);maxVolumn=maxVolumn>m?maxVolumn:m;}else{right--;int m=height[left]>height[right]?height[right]*(right-left):height[left]*(right-left);maxVolumn=maxVolumn>m?maxVolumn:m;}}return maxVolumn;    }public static int min(int a,int b){return a>b?b:a;}


0 0
原创粉丝点击