Leetcode
Leetcode
clarification -> brute force + Big O -> optimal solution + Big O -> manual test in (45 minutes)
Pattern 0: Array & Hashing
Pure Array problems... the most fundamentals
Pattern 1: Two pointers
1) left = 0, right = len(list) - 1
2) left = 0, right = 0
125. Valid Palindrome
Pattern 2: Sliding windows
Window size keep adding on the right,(right += 1) until we face a blocker,
then we remove the left edge of the window, and left += 1
Pattern 3: Next Greater Element
Here:
思路:跟上题解法类似,算出第一行和第一列的值,然后加上以后的值(找出小的)
int m = grid.length; int n = grid[0].length; int[][] dp = new int[m][n]; for(int i = 1; i < m; i++) { grid[i][0] = grid[i - 1][0] + grid[i][0]; }思路:其实很简单。iterate 2d Array 的每个element,当遇到1的时候,用DFS把周围的1都变成 '#' 或者 0, 这样我们就不会在碰到它一会儿另个途径来run 的时候.然后每次数多少个dfs过了,那就是几个岛
public class solution { public int numIsland(char[][] grid) { int island = 0; for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length;j++) { if(grid[i][j] == '1') { DFS(grid, i, j); island++; } } } return island; } private static void DFS(char[][] grid, int row, int col) { if(row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] != 1) { return; } grid[row][col] == '#'; DFS(grid, i + 1, j); DFS(grid, i, j + 1); DFS(grid, i - 1, j); DFS(grid, i, j - 1); }}