一、栈和队列
1.设计一个有getMin功能的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack; class Main { Stack<Integer> dataStack = new Stack<>(); Stack<Integer> 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; i++){ for(int j=0; j<m; j++){ if(grid[i][j] == '1'){ ans++; dfs(grid,i,j,n,m); } } } return ans; } public void dfs(char[][] mat, int x, int y, int n, int m){ if(x<0 || y<0 || x>=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; i++) for(int j=0; j<m; j++){ if(grid[i][j] == 1){ int cnt = dfs(grid,i,j,n,m); ans = Math.max(ans,cnt); } } return ans; } public int dfs(int[][] a, int x, int y, int n, int m){ int ans = 1; if(x<0 || y<0 || x>=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; } }