1
import java.util.Stack;
/*
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
/*
* 非常典型的逆波兰是,用栈解决,不多说,必须牢记
* */
public class Solution1 {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(int i=0;i<tokens.length;i++){
int a;
int b;
switch (tokens[i]){
case "+":
a = stack.pop();
b = stack.pop();
stack.push(a+b);
break;
case "-":
a = stack.pop();
b = stack.pop();
//这里注意顺序
stack.push(b-a);
break;
case "*":
a = stack.pop();
b = stack.pop();
stack.push(b*a);
break;
case "/":
a = stack.pop();
b = stack.pop();
stack.push(b/a);
break;
default:
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
2
/*Given n non-negative integers representing an elevation map where the width of each bar is 1,
compute how much water it is able to trap after raining.
For example,
Given[0,1,0,2,1,0,1,3,2,1,2,1], return6.
* The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
* In this case, 6 units of rain water (blue section) are being trapped.
* Thanks Marcos for contributing this image!
* */
/*
* 在各大公司的笔试题中看到过好多类似的题,有过经验还是很容易的,先找到柱子的最大位置,然后从两边开始
* 向这个最大位置走,期间分别记录最大的水平面,如果柱子大于这个水平面,将此柱子的高度作为最大水平面,
* 如果小于,水平面减去柱子的高度为这个柱子储存的水量
* */
public class Solution3 {
public int trap(int[] A) {
if(A.length==0||A.length==1||A.length==2){
return 0;
}
int max = A[0];
int m = 0;
for (int i = 1; i < A.length; i++) {
if(A[i]>max){
max = A[i];
m = i;
}
}
int totall = 0;
int vel = A[0];
for (int i = 1; i < m; i++) {
if (A[i]>vel){
vel = A[i];
}else {
totall = totall + vel - A[i];
}
}
vel = A[A.length-1];
for (int i = A.length-2; i > m ; i--) {
if (A[i]>vel){
vel = A[i];
}else {
totall = totall + vel - A[i];
}
}
return totall;
}
}