Skip to content

Commit 3a98c92

Browse files
committed
[Function add]
1. Add leetcode solutions.
1 parent 6c31644 commit 3a98c92

5 files changed

+348
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
## 426. Convert Binary Search Tree to Sorted Doubly Linked List
2+
3+
### Question
4+
Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.
5+
6+
Let's take the following BST as an example, it may help you understand the problem better:
7+
![Imgur](https://i.imgur.com/8fVqWEO.png)
8+
9+
We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.
10+
11+
The figure below shows the circular doubly linked list for the BST above. The "head" symbol means the node it points to is the smallest element of the linked list.
12+
![Imgur](https://i.imgur.com/meEdfw9.png)
13+
14+
Specifically, we want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. We should return the pointer to the first element of the linked list.
15+
16+
The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.
17+
![Imgur](https://i.imgur.com/lsjzbwN.png)
18+
19+
### Solutions
20+
* Method 1:
21+
```Java
22+
/*
23+
// Definition for a Node.
24+
class Node {
25+
public int val;
26+
public Node left;
27+
public Node right;
28+
29+
public Node() {}
30+
31+
public Node(int _val,Node _left,Node _right) {
32+
val = _val;
33+
left = _left;
34+
right = _right;
35+
}
36+
};
37+
*/
38+
class Solution {
39+
private Node dummy, cur;
40+
public Node treeToDoublyList(Node root) {
41+
if(root == null) return null;
42+
this.dummy = new Node(0, null, null);
43+
this.cur = dummy;
44+
dfs(root);
45+
cur.right = dummy.right;
46+
dummy.right.left = cur;
47+
return dummy.right;
48+
}
49+
private void dfs(Node node){
50+
if(node == null) return;
51+
dfs(node.left);
52+
cur.right = new Node(node.val, cur, null);
53+
cur = cur.right;
54+
dfs(node.right);
55+
}
56+
}
57+
```
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
## 564. Find the Closest Palindrome
2+
3+
### Question
4+
Given an integer n, find the closest integer (not including itself), which is a palindrome.
5+
6+
The 'closest' is defined as absolute difference minimized between two integers.
7+
8+
```
9+
Example 1:
10+
11+
Input: "123"
12+
Output: "121"
13+
```
14+
15+
Note:
16+
* The input n is a positive integer represented by string, whose length will not exceed 18.
17+
* If there is a tie, return the smaller one as answer.
18+
19+
20+
21+
### Solutions
22+
* Method 1:
23+
```Java
24+
class Solution {
25+
public String nearestPalindromic(String n) {
26+
char[] arr = n.toCharArray();
27+
int left = 0, right = arr.length - 1;
28+
while(left < right) arr[right--] = arr[left++];
29+
String palindromeString = new String(arr);
30+
String preString = findPalindrome(palindromeString, true);
31+
String postString = findPalindrome(palindromeString, false);
32+
33+
long original = Long.parseLong(n);
34+
long palindrome = Long.parseLong(palindromeString);
35+
long pre = Long.parseLong(preString);
36+
long post = Long.parseLong(postString);
37+
38+
long d1 = Math.abs(original - pre);
39+
long d2 = Math.abs(original - palindrome);
40+
long d3 = Math.abs(original - post);
41+
42+
if(original == palindrome){
43+
return d1 <= d3 ? preString: postString;
44+
}else if(original > palindrome){
45+
return d2 <= d3 ? palindromeString: postString;
46+
}else{
47+
return d1 <= d2 ? preString: palindromeString;
48+
}
49+
}
50+
private String findPalindrome(String s, boolean isPre){
51+
int k = s.length() >> 1, p = s.length() - k;
52+
int l = Integer.parseInt(s.substring(0, p));
53+
l += isPre ? -1: 1;
54+
if(l == 0) return k == 0 ? "0": "9";
55+
String left = "" + l;
56+
String right = new StringBuilder(left).reverse().toString();
57+
if(k > left.length()) right += "9";
58+
return left + right.substring(right.length() - k);
59+
}
60+
}
61+
```

leetcode/679. 24 Game.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
## 679. 24 Game
2+
3+
### Question
4+
You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through operators to get the value of 24.
5+
6+
```
7+
Example 1:
8+
9+
Input: [4, 1, 8, 7]
10+
Output: True
11+
Explanation: (8-4) * (7-1) = 24
12+
13+
Example 2:
14+
15+
Input: [1, 2, 1, 2]
16+
Output: False
17+
```
18+
19+
Note:
20+
1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
21+
2. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
22+
3. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.
23+
24+
### Solutions
25+
* Method 1: DFS
26+
```Java
27+
class Solution {
28+
public boolean judgePoint24(int[] nums) {
29+
List<Double> list = new ArrayList<Double>();
30+
for(int num : nums) list.add(num * 1D);
31+
return dfs(list);
32+
}
33+
private boolean dfs(List<Double> list){
34+
int size = list.size();
35+
if(size == 1 && Math.abs(list.get(0) - 24) < 0.0001) return true;
36+
for(int i = 0; i < size; i++){
37+
for(int j = i + 1; j < size; j++){
38+
List<Double> possibles = getPossibles(list.get(i), list.get(j));
39+
for(double p : possibles){
40+
List<Double> next = new ArrayList<>();
41+
next.add(p);
42+
for(int k = 0; k < size; k++){
43+
if(k == i || k == j) continue;
44+
next.add(list.get(k));
45+
}
46+
if(dfs(next)) return true;
47+
}
48+
}
49+
}
50+
return false;
51+
}
52+
private List<Double> getPossibles(double a, double b){
53+
List<Double> result = new ArrayList<>();
54+
result.add(a + b);
55+
result.add(a * b);
56+
result.add(a - b);
57+
result.add(b - a);
58+
result.add(a / b);
59+
result.add(b / a);
60+
return result;
61+
}
62+
}
63+
```

leetcode/753. Cracking the Safe.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
## 753. Cracking the Safe
2+
3+
### Question
4+
There is a box protected by a password. The password is n digits, where each letter can be one of the first k digits 0, 1, ..., k-1.
5+
6+
You can keep inputting the password, the password will automatically be matched against the last n digits entered.
7+
8+
For example, assuming the password is "345", I can open it when I type "012345", but I enter a total of 6 digits.
9+
10+
Please return any string of minimum length that is guaranteed to open the box after the entire string is inputted.
11+
12+
```
13+
Example 1:
14+
15+
Input: n = 1, k = 2
16+
Output: "01"
17+
Note: "10" will be accepted too.
18+
19+
Example 2:
20+
21+
Input: n = 2, k = 2
22+
Output: "00110"
23+
Note: "01100", "10011", "11001" will be accepted too.
24+
```
25+
26+
Note:
27+
1. n will be in the range [1, 4].
28+
2. k will be in the range [1, 10].
29+
3. k^n will be at most 4096.
30+
31+
32+
### Solutions
33+
* Method 1: DFS: Hamiltonion path.
34+
* Hamilton path question is visiting all of the states without repeating.
35+
* What's the path between the states in this question?
36+
* For each state, its length is n, and next node can re-use previous node's last n - 1 characters.
37+
* for example, we have 0 and 1 to use.
38+
* first node is 00, second reuses 0 and append 0 or 1.
39+
* Analyse this question
40+
* If we cannot re-use previous node, we have total length of (k ^ n) * n
41+
* Since we can re-use previous node's n - 1 character, we have the total length of k ^ n + n - 1
42+
```Java
43+
class Solution {
44+
private int expect; // total length of result.
45+
private int k;
46+
private int n;
47+
public String crackSafe(int n, int k) {
48+
this.expect = (int)Math.pow((double)k, (double)n) + n - 1;
49+
this.k = k;
50+
this.n = n;
51+
StringBuilder res = new StringBuilder();
52+
for(int i = 0; i < n; i++) res.append(0);
53+
Set<String> visited = new HashSet<>();
54+
visited.add(res.toString());
55+
dfs(res, visited);
56+
return res.toString();
57+
}
58+
private boolean dfs(StringBuilder sb, Set<String> visited){
59+
if(sb.length() == expect) return true;
60+
// sb currently saves the string and we will reuse last n - 1 characters.
61+
String pre = sb.substring(sb.length() - n + 1);
62+
for(char c = '0'; c < '0' + k; c++){
63+
String current = pre + c;
64+
if(visited.contains(current)) continue;
65+
visited.add(current);
66+
sb.append(c);
67+
if(dfs(sb, visited)) return true;
68+
sb.deleteCharAt(sb.length() - 1);
69+
visited.remove(current);
70+
}
71+
return false;
72+
}
73+
}
74+
```

leetcode/773. Sliding Puzzle.md

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
## 773. Sliding Puzzle
2+
3+
### Question
4+
On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.
5+
6+
A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
7+
8+
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
9+
10+
Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
11+
12+
```
13+
Examples:
14+
15+
Input: board = [[1,2,3],[4,0,5]]
16+
Output: 1
17+
Explanation: Swap the 0 and the 5 in one move.
18+
19+
Input: board = [[1,2,3],[5,4,0]]
20+
Output: -1
21+
Explanation: No number of moves will make the board solved.
22+
23+
Input: board = [[4,1,2],[5,0,3]]
24+
Output: 5
25+
Explanation: 5 is the smallest number of moves that solves the board.
26+
An example path:
27+
After move 0: [[4,1,2],[5,0,3]]
28+
After move 1: [[4,1,2],[0,5,3]]
29+
After move 2: [[0,1,2],[4,5,3]]
30+
After move 3: [[1,0,2],[4,5,3]]
31+
After move 4: [[1,2,0],[4,5,3]]
32+
After move 5: [[1,2,3],[4,5,0]]
33+
34+
Input: board = [[3,2,4],[1,5,0]]
35+
Output: 14
36+
```
37+
38+
Note:
39+
1. board will be a 2 x 3 array as described above.
40+
2. board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5].
41+
42+
### Solutions
43+
* Method 1: BFS shortest step questions always use bfs
44+
```Java
45+
class Solution {
46+
private static int[][] dir = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
47+
public int slidingPuzzle(int[][] board) {
48+
Set<String> visited = new HashSet<>();
49+
int step = 0;
50+
String target = "123450";
51+
StringBuilder sb = new StringBuilder();
52+
for(int[] bb : board){
53+
for(int b : bb)
54+
sb.append(b);
55+
}
56+
String initial = sb.toString();
57+
if(initial.equals(target)) return 0;
58+
Queue<String> q = new LinkedList<>();
59+
q.offer(initial);
60+
visited.add(initial);
61+
while(!q.isEmpty()){
62+
int size = q.size();
63+
step++;
64+
for(int k = 0; k < size; k++){
65+
String s = q.poll();
66+
int index = s.indexOf("0");
67+
int row = index / 3, col = index % 3;
68+
int tx = 0, ty = 0;
69+
for(int d = 0; d < 4; d++){
70+
tx = row + dir[d][0];
71+
ty = col + dir[d][1];
72+
if(tx >= 0 && tx < 2 && ty >= 0 && ty < 3){
73+
String next = swap(s, tx * 3 + ty, index);
74+
if(visited.contains(next)) continue;
75+
if(next.equals(target)) return step;
76+
q.offer(next);
77+
visited.add(next);
78+
}
79+
}
80+
}
81+
}
82+
return -1;
83+
}
84+
85+
private String swap(String s, int a, int b){
86+
char[] arr = new String(s).toCharArray();
87+
char temp = arr[a];
88+
arr[a] = arr[b];
89+
arr[b] = temp;
90+
return new String(arr);
91+
}
92+
}
93+
```

0 commit comments

Comments
 (0)