leetCode解题报告5道题(十)

题目一:Valid Number

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.


分析:

这道题目非常easy理解,可是主要要考虑到多种情况哈.

以下我们来分析下有哪些情况须要考虑到

1、空格不能出如今数字之间(即一開始我们要消除掉字符串前后的"空格",那么之后假设再出现空格那就不满足题意了)

2、小数点和e最多仅仅能出现一次("." 和"e" (或者"E")), 如:"..2"和"0e1e1"这种字符串都是不合法的.

3、字符e之前必须有数字。e之后也要有数字, 如: "e1"或者"0e"这种字符串也不合法

4、正负号要么出如今数字的最前面,要么出如今紧接着e后面("+"或者"-" 仅仅能在“去除空格之后的字符串”的首字母出现 或者 紧跟在"e"的后面出现) 如: "  +123.1  " 或者 "  -12  " 或者 " 0e+6 "或者"  10e-2 "这些都是合法的

5、"e"后面的数字不能是小数(即e之后不能出现小数点)


分析完这些全部的情况。那么我们就能够開始写代码了。看代码理解吧~~~~


AC代码:

public class Solution {
    public boolean isNumber(String s) {
        
        int start = 0;
        int len = s.length();
        int end = len-1;
        boolean flags = false;//直到处理到当前字符的时候是合法(true)还是非法(false)
        boolean exitsE = false;//是否已经存在“e”
        int doin = 0;   //小数点的个数
        //去除前面的空格 ' '
        while (start < len){
            if (s.charAt(start) == ' '){
                start++;
            }else{
                break;
            }
        }
        //去除后面的空格 ' '
        while (end >= 0){
            if (s.charAt(end) == ' '){
                end--;
            }else{
                break;
            }
        }
        //从第一个不是空格的位置開始。到最后一个不是空格的位置
        for (int index=start; index<=end; ++index){
            char c = s.charAt(index);
            //假设开头是"+"或者"-", 那么是能够的。~~~ O(∩_∩)O
            if (index == start && (s.charAt(index) == '-' || s.charAt(index) == '+')){
                continue;
            }
            //假设"+"或者"-"紧跟在"e"或者“E”之后也是能够的!

if ((s.charAt(index) == '-' || s.charAt(index) == '+') && (s.charAt(index-1) == 'e' || s.charAt(index-1) == 'E')){ flags = false; }else if(!((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E')){ //除了上面的"+"和"-"之外,假设字符不满足在 0~9 或者 . 或者 e 或者 E中的一个的话,则不合法 return false; }else{ //假设遇到数字flags则设为合法 if ((c >= '0' && c <= '9')){ flags = true; }else if (c == 'e' || c == 'E'){ //假设exitsE==true 表示之前的字符串已经出现过 e 或者 "E" 了,这样就有两个e了,不合法 if (exitsE){ return false; } exitsE = true; //假设flags == true,表示前面有出现过数字 if (flags){ flags = false;//在把flags设置为false, 用来推断e之后是否还有出现数字 }else{ return false; } }else if (c == '.'){ //e后面的数字必须是整数,则假设小数点在e之后的话,直接不合法 if (exitsE){ return false; } //假设小数点的个数大于1则不合法 doin++; if (doin > 1) return false; }else{ } } } return flags; } }



题目二:Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

分析:

这道题目的意思挺easy理解的,我们主要讲下解法:

老规矩,我喜欢通过样例来说明解法哈,假设 A=[2, 0, 2, 0, 1]       len = A.length;

我们先从第一个位置A[0]開始,然后我们用一个pos来记录如今第一个位置所能到达的最远距离。

pos = A[0] = 2;

然后我们用一个index (index < len)来记录当前的下标位置,第一个A[0]处理了之后 index++, 

假设index > pos 则表示如今这个index的位置已经是 第一个元素所不能到达的地方了,这样子的话就不可能走到最后一个元素,则返回false

假设index <= pos 则 假设 A[index] + i > pos (第一个元素能走到更远的位置了),更新一下pos的值。


AC代码:

public class Solution {
    public boolean canJump(int[] A) {
        int len = A.length;
        int index = 0;
        int pos = 0;//第一个元素能到的位置
        while (index < len){
            if (pos < index){
                //beyond
                return false;
            }else{
                //before or equals pos
                if (A[index] + index > pos){
                    pos = A[index] + index;
                }
            }
            index++;
        }
        return true;
    }
}


题目三:Jump Game II

 

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

分析:

这题跟上面的那道题比較像。仅仅只是有点像贪心法,每一步都要走最远的那种情况,所以每一次我们都须要把全部能走到的全部位置先走一遍,看哪个最远。


AC代码:

public class Solution {
    public int jump(int[] A) {
        int len = A.length;
        if (len == 1)
            return 0;
            
        int max = A[0];
        int index = 1;
        int pos = A[0];
        int n = 1;
        
        while (index < len){
            if (pos >= len-1){
                break;//假设pos已经能够到最后一个位置的话,结束
            }
            //before or equals pos
            if (A[index] + index > max && index <= pos){
                max = A[index] + index;//记录最大值
            }
            
            if (index == pos){
                if (max > pos){
                    pos = max;
                    n++;
                }
            }
            index++;
        }
        return n;
    }
}


题目四:Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

分析:

这道题目能够看做是一个动态规划的题目吧,我们举个样例

假设grid[][]=

1  2  3  4

7  8  1  3

2  5  6  10

我们从右下方的元素開始,往前推

当我们推断到  grid[2][2] == 6 时。它到右下方结点的距离为 6 + 10 = 16。 存入grid[2][2]=16;

当我们推断到 10 上方的那个元素 grid[1][3] == 3时,它到右下方结点的距离为 3 + 10 = 13, 存入grid[1][3]=13;

当推断到 grid[1][2] == 1时。 它到右下方的距离,就是 grid[1][3] 和 grid[2][2]中比較小的那个值 再加上自身的值。即grid[1][2] += min{grid[1][3] (当前元素右边的元素) , grid[2][2] (当前元素下边的元素)};


AC代码:

public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        for (int row=m-1; row>=0; row--){
            for (int col=n-1; col>=0; col--){
                //右边的列的下标
                int colRight = col + 1;
                //下边的行的行标
                int rowDown = row + 1;
                //初始值
                int rowDownValue = Integer.MAX_VALUE;
                int colRightValue = Integer.MAX_VALUE;
                
                //存在行
                if (rowDown < m){
                    rowDownValue = grid[rowDown][col];
                }
                //存在列
                if (colRight < n){
                    colRightValue = grid[row][colRight];
                }
                //取最小
                int min = rowDownValue > colRightValue ? colRightValue : rowDownValue;
                //最小等于Integer.MAX_VALUE则表示没有右边也没有下边元素,即为右下方的那个目标元素
                if (min != Integer.MAX_VALUE){
                    grid[row][col] += min;
                }
            }
        }
        return grid[0][0];
    }
}



题目五:Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.


Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].


The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.

分析:

1、暴力法:

初看题目。非常easy给人想到的方法就是暴力法,也就是说对每一个 index < len 都找到从index 往左 和 往右,直到height[index] > height[left]  和 height[index] > height[right], 然后 把int temp = height[index] * (right - left + 1) 。 假设temp > max, 则更新max的值,可是这种话一下子就TLE超时了。

TLE代码:

public class Solution {
    public int largestRectangleArea(int[] height) {
        int len = height.length;
        int max = Integer.MIN_VALUE;
        for (int i=0; i<len; ++i){
            int nowHeight = height[i];
            int left=i-1;
            while (left>=0){
                if (height[left] < nowHeight){
                    break;
                }
                --left;
            }
            int right=i+1;
            while (right<len){
                if (height[right] < nowHeight){
                    break;
                }
                ++right;
            }
            
            int allSize = (right-left+1) * nowHeight;
            if (allSize > max){
                max = allSize;
            }
        }
        return max;
    }
}



2、借助辅助栈:

竟然暴力法不行。那我们能够知道它基本的时间消耗事实上是在寻找左边的left, 和右边的right上面,这种话有没有什么办法把这块时间节省下来,在我们遍历的过程中确定好left, right的值呢?

我们採用辅助栈( 栈中存放矩形的下标 )来做这道题目能够解决它哈。

算法描写叙述:

1、定义一个空栈

2、遍历数组 index < n

2.1、遍历到index的时候,假设“栈为空”或者height[stack.peek()] <= height[index], 这时候把 index 压入到stack中,并index++

2.2、假设不满足2.1的情况,那么证明栈顶元素p相应的height值比当前index相应的height值来得小。这种话弹出栈顶元素,并算出以栈顶元素为height所能得到的最大的矩形面积。这时候就是用辅助栈的关键地方了,针对这个情况,它的left位置就是它在栈中的下一个位置(假设没有,则表示left是0,即左边界从0開始),而它的右边界right位置就是当前index的值。

看到这里,肯定迷糊了吧,想想仅仅有当  “栈为空”或者height[stack.peek()] <= height[index] 的时候我们才会把index值压入栈中。也就是说假设把栈从上往下看,必然上面的值相应的height会比以下的大或者相等,这样以下的那个元素相应的值就必然是left的值,同理由于当 当前height[stack.peek()] > height[index] , 我们才进行计算面积的工作,这样子的话这个index就是stack.peek()取到的这个位置相应height 的right右边界咯.


AC代码:

public class Solution {
    public int largestRectangleArea(int[] height) {
        int len = height.length;
        if (len == 0)
            return 0;
        int max = Integer.MIN_VALUE;
        Stack<Integer> stack = new Stack<Integer>();
        int index = 0;
        while (index < len){
            if (stack.empty() || height[(int)stack.peek()] <= height[index]){
                stack.push(index);
                index++;//这里才有++哦!

}else{ //计算面积 int popIndex = (int)stack.pop(); int allWidth = stack.empty() ? index : index-((int)stack.peek())-1; int tempValue = height[popIndex] * allWidth; if (tempValue > max){ max = tempValue; } } } //right边界都为len while (!stack.empty()){ int popIndex = (int)stack.pop(); int allWidth = stack.empty() ? len : len-((int)stack.peek())-1; int tempValue = height[popIndex] * allWidth; if (tempValue > max){ max = tempValue; } } return max; } }


原文地址:https://www.cnblogs.com/jzssuanfa/p/6991850.html