一、栈和队列
1.设计一个有getMin功能的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack;class Main { StackdataStack = new Stack<>(); Stack minStack = new Stack<>(); public static void main(String[] args) { Main stack = new Main(); stack.push(11); stack.push(2); stack.pop(); stack.push(70); stack.push(51); System.out.println(stack.getMin()); stack.push(4); stack.push(113); System.out.println(stack.getMin()); } public void push(int num) { if(minStack.isEmpty()) minStack.push(num); if(num > minStack.peek()) { minStack.push(minStack.peek()); } else { minStack.push(num); } dataStack.push(num); } public int pop() { if(dataStack.isEmpty()) { throw new RuntimeException("Your stack is empty."); } minStack.pop(); return dataStack.pop(); } public int getMin() { if(minStack.isEmpty()) { throw new RuntimeException("Your stack is empty."); } return minStack.peek(); }}
class Solution { public int numIslands(char[][] grid) { if(grid == null || grid.length <= 0 || grid[0].length <= 0){ return 0; } int ans = 0; int n = grid.length; int m = grid[0].length; for(int i=0; i=n || y>=m || mat[x][y] != '1') return; mat[x][y]='2'; dfs(mat,x+1,y,n,m); dfs(mat,x-1,y,n,m); dfs(mat,x,y+1,n,m); dfs(mat,x,y-1,n,m); }}
class Solution { public int maxAreaOfIsland(int[][] grid) { if(grid==null || grid.length==0 || grid[0].length==0) return 0; int n = grid.length; int m = grid[0].length; int ans = 0; for(int i=0; i=n || y>=m || a[x][y] != 1) return 0; a[x][y] = 2; ans += dfs(a,x+1,y,n,m); ans += dfs(a,x-1,y,n,m); ans += dfs(a,x,y+1,n,m); ans += dfs(a,x,y-1,n,m); return ans; }}