0%

剑指offer

记录leetcode里的剑指offer题目

52 两个链表的第一个公共节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
* @lc app=leetcode.cn id=160 lang=java
*
* [160] 相交链表
*/

// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
/**
* 两个指针走互相走过的路即可
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode tempA = headA;
ListNode tempB = headB;
while (tempA != tempB) {
tempA = tempA == null ? headB : tempA.next;
tempB = tempB == null ? headA : tempB.next;
}
return tempA;
}
}
// @lc code=end

5 替换空格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 剑指offer刷题
*/
class Solution {
public String replaceSpace(String s) {
int len = s.length();
char[] array = new char[len * 3];
int size = 0;
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c == ' ') {
array[size++] = '%';
array[size++] = '2';
array[size++] = '0';
} else {
array[size++] = c;
}
}
String newStr = new String(array, 0, size);
return newStr;
}
}

6 从尾到头打印链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Stack;

/**
* 剑指offer刷题
*/
/**
* 用栈解决即可,先进后出
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}

7重建二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.HashMap;
import java.util.Map;

/*
* @lc app=leetcode.cn id=105 lang=java
*
* [105] 从前序与中序遍历序列构造二叉树
*/

// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/**
* 健表示元素节点的值,值表示元素在中序遍历中出现的位置
**/
private Map<Integer,Integer> indexMap = new HashMap<>();

public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = preorder.length;
for (int i = 0; i < n; i++) {
indexMap.put(inorder[i], i);
}
return myBuildTree(preorder, inorder, 0, n-1, 0, n-1);
}

public TreeNode myBuildTree(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
if (preLeft > preRight) {
return null;
}
//前序遍历的第一个节点就是根节点
int pre_root = preLeft;
//在中序遍历中定位根节点
int in_root = indexMap.get(preorder[pre_root]);

//先建立根节点
TreeNode root = new TreeNode(preorder[pre_root]);
//得到左子树节点数目
int size_left = in_root - inLeft;
//递归构造左子树
root.left = myBuildTree(preorder, inorder, preLeft+1, preLeft+size_left, inLeft, in_root-1);
//递归构造右子树
root.right = myBuildTree(preorder, inorder, preLeft+1+size_left, preRight, in_root+1, inRight);
return root;
}
}
// @lc code=end

-------------本文结束感谢您的阅读-------------