更新leetcode代码

This commit is contained in:
xiongraorao 2018-08-23 11:52:50 +08:00
parent 191edeeaee
commit 8ad4c408e4
18 changed files with 932 additions and 16 deletions

View File

@ -0,0 +1,45 @@
package com.raorao.leetcode.q017;
import java.util.ArrayList;
import java.util.List;
/**
* 电话键盘组合.
*
* @author Xiong Raorao
* @since 2018-08-22-18:46
*/
public class PhoneNumber {
private final static String[] KEYS = new String[] {"", "", "abc", "def", "ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
public static void main(String[] args) {
List<String> ret = new PhoneNumber().letterCombinations("23");
System.out.println(ret);
}
public List<String> letterCombinations(String digits) {
List<String> ret = new ArrayList<>();
int[] index = new int[digits.length()];
for (int i = 0; i < index.length; i++) {
index[i] = digits.charAt(i) - '0';
}
process(new StringBuilder(), ret, index);
return ret;
}
private void process(StringBuilder prefix, List<String> ret, int[] index) {
if (prefix.length() == index.length) {
ret.add(prefix.toString());
return;
}
for (char c : KEYS[index[prefix.length()]].toCharArray()) {
prefix.append(c);
process(prefix, ret, index);
prefix.deleteCharAt(prefix.length() - 1);
}
}
}

View File

@ -0,0 +1,70 @@
package com.raorao.leetcode.q037;
/**
* 数独问题.
*
* @author Xiong Raorao
* @since 2018-08-23-9:30
*/
public class Shudu {
private boolean[][] rowsUsed = new boolean[9][10];
private boolean[][] colsUsed = new boolean[9][10];
private boolean[][] cubesUsed = new boolean[9][10];
private char[][] board;
public static void main(String[] args) {
}
public void solveSudoku(char[][] board) {
this.board = board;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
continue;
}
int num = board[i][j] - '0';
rowsUsed[i][num] = true;
colsUsed[j][num] = true;
cubesUsed[cubeNum(i, j)][num] = true;
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
backtracking(i, j);
}
}
}
private boolean backtracking(int row, int col) {
while (row < 9 && board[row][col] != '.') {
row = col == 8 ? row + 1 : row;
col = col == 8 ? 0 : col + 1;
}
if (row == 9) {
return true;
}
for (int num = 1; num <= 9; num++) {
if (rowsUsed[row][num] || colsUsed[col][num] || cubesUsed[cubeNum(row, col)][num]) {
continue;
}
rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = true;
board[row][col] = (char) (num + '0');
if (backtracking(row, col)) {
return true;
}
board[row][col] = '.';
rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = false;
}
return false;
}
private int cubeNum(int i, int j) {
int r = i / 3;
int c = j / 3;
return r * 3 + c;
}
}

View File

@ -0,0 +1,43 @@
package com.raorao.leetcode.q046;
import java.util.ArrayList;
import java.util.List;
/**
* 排列.
*
* @author Xiong Raorao
* @since 2018-08-23-8:58
*/
public class Permutation {
public static void main(String[] args) {
int[] input = new int[] {1, 2, 3};
new Permutation().permute(input);
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> permutes = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
back(nums, new ArrayList<>(), permutes, visited);
return permutes;
}
private void back(int[] arr, List<Integer> level, List<List<Integer>> lists,
boolean[] visited) {
if (level.size() == arr.length) {
lists.add(new ArrayList<>(level));
return;
}
for (int i = 0; i < arr.length; i++) {
if(visited[i]){
continue;
}
visited[i] = true;
level.add(arr[i]);
back( arr, level, lists, visited);
level.remove(level.size() - 1);
visited[i] = false;
}
}
}

View File

@ -0,0 +1,41 @@
package com.raorao.leetcode.q064;
import java.util.Arrays;
/**
* 矩阵最小路径和.
*
* @author Xiong Raorao
* @since 2018-08-23-10:56
*/
public class MinPathSum {
public static void main(String[] args) {
int[][] grid = new int[][] {
{1, 3, 1},
{1, 5, 1},
{4, 2, 1}};
int res = new MinPathSum().minPathSum(grid);
System.out.println(res);
}
public int minPathSum(int[][] grid) {
if (grid == null) {
return 0;
}
int rowLen = grid.length;
int colLen = grid[0].length;
int[] res = new int[colLen + 1];
Arrays.fill(res, Integer.MAX_VALUE);
res[1] = 0;
for (int i = 1; i <= rowLen; i++) {
for (int j = 1; j <= colLen; j++) {
//当前点的最小路径和为 : 从左边和上边选择最小的路径和再加上当前点的值
//res[j]没更新之前就表示i-1行到第j个元素的最小路径和
//因为是从左往右更新,res[j-1]表示i行第j-1个元素的最小路径和
res[j] = Math.min(res[j], res[j - 1]) + grid[i - 1][j - 1];
}
}
return res[colLen];
}
}

View File

@ -0,0 +1,62 @@
package com.raorao.leetcode.q079;
/**
* 在矩阵中寻找字符串.
*
* @author Xiong Raorao
* @since 2018-08-23-7:44
*/
public class WordSearch {
private static final int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private static int m;
private static int n;
public static void main(String[] args) {
char[][] input = new char[][] {
{'A', 'B', 'C', 'E'},
{'S', 'F', 'C', 'S'},
{'A', 'D', 'E', 'E'},
};
String word = "ABCCED";
System.out.println(new WordSearch().exist(input, word));
}
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0) {
return false;
}
m = board.length;
n = board[0].length;
boolean[][] hasVisited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (back(board, 0, i, j, hasVisited, word)) {
return true;
}
}
}
return false;
}
private boolean back(char[][] board, int current, int i, int j, boolean[][] hasVisited,
String word) {
if (current == word.length()) {
return true;
}
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word.charAt(current)
|| hasVisited[i][j]) {
return false;
}
hasVisited[i][j] = true;
for (int[] d : direction) {
if (back(board, current + 1, i + d[0], j + d[1], hasVisited, word)) {
return true;
}
}
hasVisited[i][j] = false;
return false;
}
}

View File

@ -0,0 +1,54 @@
package com.raorao.leetcode.q093;
import java.util.ArrayList;
import java.util.List;
/**
* ip地址的划分.
*
* @author Xiong Raorao
* @since 2018-08-22-20:38
*/
public class RestoreIP {
public static void main(String[] args) {
String input = "25525511135";
List<String> ret = new RestoreIP().restoreIpAddresses(input);
ret.forEach(e -> System.out.print(e + " "));
}
public List<String> restoreIpAddresses(String s) {
List<String> ret = new ArrayList<>();
process(0, new StringBuilder(), ret, s);
return ret;
}
/**
* @param k 表示当前已经分割的ip段
*/
private void process(int k, StringBuilder sb, List<String> ret, String s) {
if (k == 4 || s.length() == 0) {
if (k == 4 && s.length() == 0) {
ret.add(sb.toString());
}
return;
}
for (int i = 0; i < s.length() && i <= 2; i++) {
if (i != 0 && s.charAt(0) == '0') {
break;
}
String part = s.substring(0, i + 1);
if (Integer.valueOf(part) <= 255) {
if (sb.length() != 0) {
part = "." + part;
}
sb.append(part);
process(k + 1, sb, ret, s.substring(i + 1));
sb.delete(sb.length() - part.length(), sb.length());
}
}
}
}

View File

@ -0,0 +1,91 @@
package com.raorao.leetcode.q102;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
/**
* 二叉树的层次遍历.
*
* @author Xiong Raorao
* @since 2018-08-22-10:43
*/
public class LevelOrder {
public static void main(String[] args) {
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if (root == null) {
return ret;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> levelList = new ArrayList<>();
while (levelSize-- > 0) {
TreeNode node = queue.poll();
if (node != null) {
levelList.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
ret.add(levelList);
}
return ret;
}
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if (root == null) {
return ret;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
Stack<List<Integer>> listStack = new Stack<>();
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> levelList = new ArrayList<>();
while (levelSize-- > 0) {
TreeNode node = queue.poll();
if (node != null) {
levelList.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
listStack.add(levelList);
}
while (!listStack.isEmpty()) {
ret.add(listStack.pop());
}
return ret;
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}

View File

@ -0,0 +1,57 @@
package com.raorao.leetcode.q111;
import java.util.LinkedList;
import java.util.Queue;
/**
* 求二叉树的最小深度.
*
* @author Xiong Raorao
* @since 2018-08-22-14:33
*/
public class BTreeDepth {
public static void main(String[] args) {
}
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) {
return 0;
}
queue.add(root);
int level = 1;
while (!queue.isEmpty()) {
int levelSize = queue.size();
while (levelSize-- > 0) {
TreeNode node = queue.poll();
if (node != null) {
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
if (node.left == null && node.right == null) {
return level;
}
}
}
level++;
}
return level;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}

View File

@ -0,0 +1,95 @@
package com.raorao.leetcode.q127;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 单词接龙.
*
* @author Xiong Raorao
* @since 2018-08-22-10:02
*/
public class WordLadder {
public static void main(String[] args) {
String beginWord = "hit";
String endWord = "cog";
//List<String> wordList = Arrays.asList("hot", "dot", "dog", "lot", "log", "cog");
List<String> wordList = new ArrayList<>();
wordList.add("hot");
wordList.add("dot");
wordList.add("lot");
wordList.add("log");
wordList.add("cog");
int result = new WordLadder().ladderLength(beginWord, endWord, wordList);
System.out.println(result);
}
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
wordList.add(beginWord);
int N = wordList.size();
int start = N - 1;
int end = 0;
while (end < N && !wordList.get(end).equals(endWord)) {
end++;
}
if (end == N) {
return 0;
}
List<Integer>[] graphic = buildGraphic(wordList);
return getShortestPath(graphic, start, end);
}
private List<Integer>[] buildGraphic(List<String> wordList) {
int N = wordList.size();
List<Integer>[] graphic = new List[N];
for (int i = 0; i < N; i++) {
graphic[i] = new ArrayList<>();
for (int j = 0; j < N; j++) {
if (isConnect(wordList.get(i), wordList.get(j))) {
graphic[i].add(j);
}
}
}
return graphic;
}
private boolean isConnect(String s1, String s2) {
int diffCnt = 0;
for (int i = 0; i < s1.length() && diffCnt <= 1; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
diffCnt++;
}
}
return diffCnt == 1;
}
private int getShortestPath(List<Integer>[] graphic, int start, int end) {
Queue<Integer> queue = new LinkedList<>();
boolean[] marked = new boolean[graphic.length];
queue.add(start);
marked[start] = true;
int path = 1;
while (!queue.isEmpty()) {
int size = queue.size();
path++;
while (size-- > 0) {
int cur = queue.poll();
for (int next : graphic[cur]) {
if (next == end) {
return path;
}
if (marked[next]) {
continue;
}
marked[next] = true;
queue.add(next);
}
}
}
return 0;
}
}

View File

@ -0,0 +1,82 @@
package com.raorao.leetcode.q130;
import java.util.LinkedList;
import java.util.Queue;
/**
* 被围绕的区域.
*
* @author Xiong Raorao
* @since 2018-08-22-14:53
*/
public class SurroundedRegion {
private static Queue<Integer> queue = null;
private static int rows = 0;
private static int cols = 0;
public static void main(String[] args) {
char[][] board = new char[][] {
{'X', 'X', 'X', 'X'},
{'X', 'O', 'O', 'X'},
{'X', 'X', 'O', 'X'},
{'X', 'O', 'X', 'X'}};
new SurroundedRegion().solve(board);
}
public void solve(char[][] board) {
if (board.length == 0 || board[0].length == 0) {
return;
}
queue = new LinkedList<Integer>();
rows = board.length;
cols = board[0].length;
for (int i = 0; i < rows; i++) { // **important**
enqueue(i, 0, board);
enqueue(i, cols - 1, board);
}
for (int j = 1; j < cols - 1; j++) { // **important**
enqueue(0, j, board);
enqueue(rows - 1, j, board);
}
// 把所有边界为O的元素的位置以及和边界连通的O放到队列中去已经放入队列的改为'D'
while (!queue.isEmpty()) {
int cur = queue.poll();
int x = cur / cols,
y = cur % cols;
if (board[x][y] == 'O') {
board[x][y] = 'D';
}
enqueue(x - 1, y, board);
enqueue(x + 1, y, board);
enqueue(x, y - 1, board);
enqueue(x, y + 1, board);
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'D') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
queue = null;
board = null;
rows = 0;
cols = 0;
}
public void enqueue(int x, int y, char[][] board) {
if (x >= 0 && x < rows && y >= 0 && y < cols && board[x][y] == 'O') {
queue.offer(x * cols + y);
}
}
}

View File

@ -0,0 +1,33 @@
package com.raorao.leetcode.q198;
/**
* 强盗抢劫.
*
* @author Xiong Raorao
* @since 2018-08-23-10:09
*/
public class Robber {
public static void main(String[] args) {
int[] input = new int[] {1, 2, 3, 1};
int result = new Robber().rob(input);
System.out.println(result);
}
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
int pre1 = 0;
int pre2 = 0;
int pre3 = 0;
for (int i = 0; i < n; i++) {
int cur = Math.max(pre2, pre3) + nums[i];
pre3 = pre2;
pre2 = pre1;
pre1 = cur;
}
return Math.max(pre1, pre2);
}
}

View File

@ -0,0 +1,50 @@
package com.raorao.leetcode.q200;
/**
* 求岛屿的个数.
*
* @author Xiong Raorao
* @since 2018-08-22-16:53
*/
public class NumIslands {
private final int[][] directions = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) {
char[][] grid = new char[][] {
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'}};
int result = new NumIslands().numIslands(grid);
System.out.println(result);
}
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
int islandNum = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
islandNum++;
}
}
}
return islandNum;
}
private void dfs(char[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
for (int[] d : directions) {
dfs(grid, i + d[0], j + d[1]);
}
}
}

View File

@ -0,0 +1,66 @@
package com.raorao.leetcode.q257;
import java.util.ArrayList;
import java.util.List;
/**
* 输出二叉树的叶子节点的路径.
*
* @author Xiong Raorao
* @since 2018-08-23-8:24
*/
public class BinaryTreePath {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode left = new TreeNode(2);
left.right = new TreeNode(5);
TreeNode right = new TreeNode(3);
root.left = left;
root.right = right;
List<String> str = new BinaryTreePath().binaryTreePaths(root);
str.forEach(System.out::println);
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> path = new ArrayList<>();
if (root == null) {
return path;
}
List<TreeNode> values = new ArrayList<>();
back(values, root, path);
return path;
}
private void back(List<TreeNode> values, TreeNode root, List<String> path) {
if (root == null) {
return;
}
values.add(root);
if (root.left == null && root.right == null) {
path.add(build(values));
}
back(values, root.left, path);
back(values, root.right, path);
values.remove(root);
}
private String build(List<TreeNode> node) {
StringBuilder sb = new StringBuilder();
node.forEach(e -> sb.append(e.val).append("->"));
String tmp = sb.toString();
return tmp.substring(0, tmp.length() - 2);
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}

View File

@ -0,0 +1,27 @@
package com.raorao.leetcode.q279;
import java.util.ArrayList;
import java.util.List;
/**
* 完全平方数.
*
* 题目描述给定正整数 n找到若干个完全平方数比如 1, 4, 9, 16, ...使得它们的和等于 n你需要让组成和的完全平方数的个数最少
*
* @author Xiong Raorao
* @since 2018-08-22-9:29
*/
public class PerfectSquare {
public static void main(String[] args) {
}
private static List<Integer> generate(int n) {
List<Integer> ret = new ArrayList<>();
for (int i = 1; i * i < n; i++) {
ret.add(i * i);
}
return ret;
}
}

View File

@ -0,0 +1,44 @@
package com.raorao.leetcode.q547;
/**
* 朋友圈.
*
* @author Xiong Raorao
* @since 2018-08-22-17:08
*/
public class FriendCycle {
public static void main(String[] args) {
int[][] M = new int[][] {
{1, 1, 0},
{1, 1, 0},
{0, 0, 1}};
int result = new FriendCycle().findCircleNum(M);
System.out.println(result);
}
public int findCircleNum(int[][] M) {
if (M == null || M.length == 0) {
return 0;
}
int n = M.length;// 朋友圈人数
int num = 0;
boolean[] hasVisited = new boolean[n];
for (int i = 0; i < n; i++) {
if (!hasVisited[i]) {
dfs(M, hasVisited, i);
num++;
}
}
return num;
}
private void dfs(int[][] M, boolean[] hasVisited, int i) {
hasVisited[i] = true;
for (int k = 0; k < M.length; k++) {
if (M[i][k] == 1 && !hasVisited[k]) {
dfs(M, hasVisited, k);
}
}
}
}

View File

@ -0,0 +1,55 @@
package com.raorao.leetcode.q695;
/**
* 岛屿的最大面积.
*
* @author Xiong Raorao
* @since 2018-08-22-16:06
*/
public class MaxArea {
private final int[][] directions = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) {
int[][] grid = new int[][] {
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}};
int result = new MaxArea().maxAreaOfIsland(grid);
System.out.println(result);
}
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
if (grid == null || grid.length == 0) {
return 0;
}
int row = grid.length;
int col = grid[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
maxArea = Math.max(maxArea, dfs(grid, i, j));
}
}
return maxArea;
}
private int dfs(int[][] grid, int m, int n) {
if (m < 0 || m >= grid.length || n < 0 || n >= grid[0].length || grid[m][n] == 0) {
return 0;
}
int area = 1;
grid[m][n] = 0; // 统计过了就置零
for (int[] d : directions) {
area += dfs(grid, m + d[0], n + d[1]);
}
return area;
}
}

View File

@ -39,6 +39,8 @@ Java后端开发大数据、分布式应用等
京东 | 8.4 | 8.20 | <li>简历截止8.30</li><li>笔试时间 9.9</li><li>面试时间 9.16-9.20</li>
微众银行| 8.20 | 8.20 |
华为 |8.1 | 8.21
百度 | 8.22 | 8.22(新投递) |
网易 | 8.22 | 8.22(新投递) |
# 2 复习内容

View File

@ -2505,24 +2505,23 @@ Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes
题目描述:求从矩阵的左上角到右下角的最小路径和,每次只能向右和向下移动。
```java
public int minPathSum(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
if (grid == null) {
return 0;
}
int m = grid.length, n = grid[0].length;
int[] dp = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0) {
dp[j] = dp[j - 1];
} else {
dp[j] = Math.min(dp[j - 1], dp[j]);
}
dp[j] += grid[i][j];
int rowLen = grid.length;
int colLen = grid[0].length;
int[] res = new int[colLen + 1];
Arrays.fill(res, Integer.MAX_VALUE);
res[1] = 0;
for (int i = 1; i <= rowLen; i++) {
for (int j = 1; j <= colLen; j++) {
//当前点的最小路径和为 : 从左边和上边选择最小的路径和再加上当前点的值
//res[j]没更新之前就表示i-1行到第j个元素的最小路径和
//因为是从左往右更新,res[j-1]表示i行第j-1个元素的最小路径和
res[j] = Math.min(res[j], res[j - 1]) + grid[i - 1][j - 1];
}
}
return dp[n - 1];
}
return res[colLen];
```
**矩阵的总路径数**