1.有效的括号
2.每日温度:单调栈
class Solution {
public int[] dailyTemperatures(int[] T) {
if (T==null||T.length==0){
return null;
}
Stack<Integer> stack = new Stack<Integer>();
int[] ans = new int[T.length];
for (int i= T.length-1;i>=0;i--){
while (!stack.isEmpty()&&T[i]>=T[stack.peek()]){
stack.pop();
}
ans[i]=stack.isEmpty()?0:stack.peek()-i;
stack.push(i);
}
return ans;
}
}
3.逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
int a, b;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
switch (tokens[i]) {
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;
case "/":
a = stack.pop();
b = stack.pop();
stack.push(b/a);
break;
default:
stack.push(Integer.valueOf(tokens[i]));
break;
}
}
return stack.pop();
}
}
4.岛屿数量 DFS
class Solution {
public int numIslands(char[][] grid) {
if (grid.length==0||grid==null){
return 0;
}
int count = 0;
int len1 = grid.length,len2 = grid[0].length;
for(int i =0;i<len1;i++){
for (int j = 0;j<len2; j++){
if (grid[i][j]=='1'){
count++;
dfs(grid,i,j,len1,len2);
}
}
}
return count;
}
private void dfs(char[][] grid, int i, int j, int len1, int len2) {
Queue<Integer> c = new LinkedList<>();
grid[i][j]='0';
if (i-1>=0&&grid[i-1][j]=='1'){
dfs(grid, i-1, j, len1, len2);
}
if (i+1<len1&&grid[i+1][j]=='1'){
dfs(grid, i+1, j, len1, len2);
}
if (j-1>=0&&grid[i][j-1]=='1'){
dfs(grid, i, j-1, len1, len2);
}
if (j+1<len2&&grid[i][j+1]=='1'){
dfs(grid, i, j+1, len1, len2);
}
}
}
5.目标和 递归
class Solution {
private int count = 0;
public int findTargetSumWays(int[] nums, int S) {
sum(nums, 0, 0, S);
return count;
}
private void sum(int[] nums, int i, int i1, int s) {
if (i==nums.length){
if (i1==s){
count++;
}
}else {
sum(nums, i+1, i1+nums[i],s);
sum(nums, i+1, i1-nums[i],s);
}
}
}
6.二叉树的中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> temp = new ArrayList<>();
if(root==null){
return temp;
}
DFS(root,temp);
return temp;
}
private void DFS(TreeNode root, List<Integer> temp) {
if (root.left!=null){
DFS(root.left, temp);
}
temp.add(root.val);
if (root.right!=null){
DFS(root.right, temp);
}
}
}
class Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Stack<TreeNode> data = new Stack<>();
TreeNode temp = root;
while (!data.isEmpty() || temp != null) {
while (temp != null) {
data.push(temp);
temp = temp.left;
}
temp = data.pop();
ans.add(temp.val);
temp = temp.right;
}
return ans;
}
}
7.克隆图死活看不懂啥意思,暂时放弃